/*
javascript for recipe features.
*/

var LAB = '&lt;' // <
var RAB = '&gt;' // >

var g_curSelIndex = -1
var g_curSelField = ''
var g_ed_urcp_cur_sel_index = undefined
//var g_cur_urcp_col_array = []
var g_cur_ed_rcp_loc = ''
var g_rcpHeaderId = -1

/*
g_cur_urcp member:
	- INFO
	- HEAD
	- COLS
	- ROWS
*/
var g_cur_urcp = {}

/*
g_cur_prcp member:
	- ROWS
*/
var g_cur_prcp = {}

var g_cur_eq_unit_list = []

var g_prcp_sel_row = -1
var g_prcp_sel_field = ''
var g_prcp_sel_index = undefined

var g_cmp_unit_type = ''
var g_cmp_sel_cur_tree_node_type = ''
var g_copy_sel_cur_tree_node_type = ''
var g_cmp_eq_1 = ''
var g_cmp_rcpfn_1 = ''
var g_cmp_loc_1 = ''
var g_cmp_eq_2 = ''
var g_copy_eq_2 = ''
var g_cmp_rcpfn_2 = ''
var g_cmp_loc_2 = 'eq'
var eqn = ''
var copy_rcp_type = ''
var copy_unit_type = ''
var copy_gird = ''
var copy_path_1 = ''
var copy_path_2 = ''
var copy_eqn1 = ''
var copy_eqn2 = ''
var old_name = ''
var new_name = ''
var rename_type = ''
var rename_unit_type = ''
var rename_path = ''
var dbclick_type = ''

// 2019-06-26 11:11, jxb
function add_log_to_server(eqName, opType, opContent)
{
	var userLogin = GetCookie('ams_user_name');
	$.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: getWebServiceUrl("setUserOpLogs"),
		data:JSON.stringify({
			"loginUser":userLogin,
			"eqName":eqName,
			"opType":opType,
			"opContent":opContent
		}),
		dataType: 'json',
		success: function (json_data) {
		},
		error: function (response) {
			$.messager.alert("Error", "Error: " + response.responseText, "error");
		}
	});
}

function reset_cur_urcp_obj()
{
	g_cur_urcp = {}
	g_cur_urcp['INFO'] = undefined
	g_cur_urcp['HEAD'] = undefined
	g_cur_urcp['COLS'] = undefined
	g_cur_urcp['ROWS'] = undefined
}

function __prcp_ed_fill_urcp_list(row)
{
//	getEqRecipeList
  var eqn = parent.$("#eq_name").val()
	var __row = $('#ed_prcp_eq_unit_list').datalist('getSelected')
	if (ams_is_sim_mode()) {
		// $.getJSON('recipe_list_eq_unit_01.json', function(json_data){
		// 	$('#ed_prcp_eq_urcp_list').treegrid({
		// 		data:json_data.rows,
		// 		textField:'name',
		// 		valueField:'name'
		// 	})
		// })
		$('#ed_prcp_eq_urcp_list').treegrid({
			url : 'recipe_list_eq_unit_01.json',
			idField : 'id',
			treeField :'name'
		})
	} else {
		// TODO: getEqRecipeList
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			// url: getWebServiceUrl("getEquipRecipeByUnitName"),
			url: getWebServiceUrl("getEqRecipeList"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpType":"unit",
				"unitName":__row.val,
				"location":false
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))

				$('#ed_prcp_eq_urcp_list').treegrid({
					data:JSON.parse(json_data.d),
					idField : 'id',
					treeField : 'name'
				})
				
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function on_page_load()
{
	// 2019-06-26 11:12, jxb
	// Reference other js documents.
	new_element=document.createElement("script");
	new_element.setAttribute("type","text/javascript");
	new_element.setAttribute("src","../js2/loginCookies.js");
	document.body.appendChild(new_element);
	
	$('#cmp_unit_rcp_list').treegrid({
		onSelect: function(row) {
			var __row = $('#cmp_unit_rcp_list').treegrid('getSelected')
			var childrenRow = isLeaf(cmp_unit_rcp_list,__row.id)
			if(childrenRow != ''){
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else{
			g_cmp_rcpfn_2 = __row.name
			document.getElementById("label_rcp_2").innerHTML = g_cmp_eq_2 + ' / ' + g_cmp_rcpfn_2 + ' [' + g_cmp_loc_2 + ']'
		}}
	})

	$('#copy_unit_rcp_list').treegrid({
		onSelect: function(row) {
			var __row_01 = $('#copy_unit_rcp_list').treegrid('getSelected')
			var childrenRow = isLeaf(copy_unit_rcp_list,__row_01.id)
			if(childrenRow == ''){
				$.messager.alert("Tips", "Select a path folder please.", "info");
				return
			}else{
				var row2 = $('#grp_eq_tree_01').tree('getSelected')
				// copy_eqn2 = row2.text
				copy_path_2 = getFullPathName(copy_unit_rcp_list,row.name+'/',row.id)
				g_copy_rcpfn_2 = __row_01.name
				document.getElementById("path_rcp_2").innerHTML = copy_path_2;//g_cmp_eq_2 + ' / ' + g_copy_rcpfn_2 
		}}
	})

	$('#ed_prcp_eq_unit_list').datalist({
		onSelect: function(row) {
			__prcp_ed_fill_urcp_list(row)
		}
	})
	
	// 20190613 start
	$('#rcp_dummy_list').datalist({
		onSelect: function(row) {
			var cur_row = $('#rcp_dummy_list').datalist('getSelected')
			__rcp_dummy_show_recipe(cur_row.name)
		}
	})
	rcp_dummy_init_mouse_event()
	// 20190613 end

	$.extend($.fn.datagrid.methods, {
		editCell: function(jq,param){
			return jq.each(function(){
				var opts = $(this).datagrid('options');
				var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
				for(var i=0; i<fields.length; i++){
					var col = $(this).datagrid('getColumnOption', fields[i]);
					col.editor1 = col.editor;
					if (fields[i] != param.field){
						col.editor = null;
					}
				}
				$(this).datagrid('beginEdit', param.index);
				var ed = $(this).datagrid('getEditor', param);
				if (ed){
					if ($(ed.target).hasClass('textbox-f')){
						$(ed.target).textbox('textbox').focus();
					} else {
						$(ed.target).focus();
					}
				}
				for(var i=0; i<fields.length; i++){
					var col = $(this).datagrid('getColumnOption', fields[i]);
					col.editor = col.editor1;
				}
			});
		},
		enableCellEditing: function(jq){
			return jq.each(function(){
				var dg = $(this)
				var opts = dg.datagrid('options')
				opts.oldOnDblClickCell = opts.onDblClickCell
				opts.onClickCell = function(index, field) {
					g_ed_urcp_cur_sel_index = index
				}
				opts.onDblClickCell = function(index, field){
					if (g_cur_ed_rcp_loc != 'server') {
						return
					}
					var vCur = $('#table_unit_rcp').datagrid('getRows')[index][field]
					var col = $('#table_unit_rcp').datagrid('getColumnOption', field)
					if ("enum" in col) {
						g_curSelIndex = index
						g_curSelField = field
						$('#value_dlg').window('open')
						var val_array = col["enum"].split("|")
						$('#val_list').datalist('loadData',[])
						for (var k = 0; k < val_array.length; k++) {
							$('#val_list').datalist('appendRow',{
									value:val_array[k],
									text:val_array[k]
								})
							if (vCur == val_array[k]) {
								$('#val_list').datalist('selectRow',k)
							}
						}
						return
					}
					if (opts.editIndex != undefined){
						if (dg.datagrid('validateRow', opts.editIndex)){
							dg.datagrid('endEdit', opts.editIndex)
							opts.editIndex = undefined
						} else {
							return
						}
					}
					
					dg.datagrid('selectRow', index).datagrid('editCell', {
						index: index,
						field: field
					})
					
					opts.editIndex = index
					opts.oldOnDblClickCell.call(this, index, field)
				}
			});
		}
	});

	$(function(){
		$('#table_unit_rcp').datagrid().datagrid('enableCellEditing')
	})

	$(function () {
    $('#window_unit_rcp').window({
        onBeforeClose: function () {
      		if (g_cur_urcp['HEAD'] != undefined)
					{
							for (var i = 1; i <= g_cur_urcp['HEAD'].length; i++) {
								document.getElementById('urcp_hv_' + i).style.display = 'none'
								document.getElementById('urcp_hn_' + i).style.display = 'none'
						}
						// for (var i = 1; i <= g_cur_urcp['INFO'].length; i++){
							// document.getElementById('urcp_in_' + i).style.display = 'none'
							// document.getElementById('urcp_iv_' + i).style.display = 'none'
						// }
					}
        }
    });
  });
  
  set_recipe_group('eq', false);
	set_recipe_group('server', false);
	// reload_rcp_list('eq', 'process')
	load_rcp_list('eq', 'process') // TODO: load again to prevent columns shifting.
	load_rcp_list('server', 'process')
	load_rcp_list('eq','unit')
	load_rcp_list('server','unit')
	load_rcp_list('eq','pump')
	load_rcp_list('server','pump')
}

function set_recipe_group(location, bForceSame)
{
	eqn = parent.$("#eq_name").val();
	var grp = (location == 'eq') ? $("#rcp-group-equ").val() : $("#rcp-group-svr").val();
	var loc = (location == 'eq') ? false : true;
	$.ajax({
	type: 'POST',
	contentType: 'application/json',
	url: getWebServiceUrl("setRecipeGroup"), 
	async:false,
	data:JSON.stringify({
		"eqName": eqn,
		"grpName":grp,
		"location":loc
	}),
	dataType: 'json',
	success: function (json_data) {
		//console.log(JSON.parse(json_data.d))
		},
		error: function (response) {
			alert('Error: ' + response.responseText)
		}
	})
	
	if (bForceSame == true){
		$.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: getWebServiceUrl("setRecipeGroup"), 
		data:JSON.stringify({
			"eqName": eqn,
			"grpName":grp,
			"location":!loc
		}),
		dataType: 'json',
		success: function (json_data) {
			//console.log(JSON.parse(json_data.d))
			},
			error: function (response) {
				alert('Error: ' + response.responseText)
			}
		})
	}
	return grp;
}

function on_rcp_open(location)
{
	var _grid_name = (location == 'eq') ? '#eq_rcp_tabs' : '#server_rcp_tabs'
	var tab = $(_grid_name).tabs('getSelected')
	var index = $(_grid_name).tabs('getTabIndex',tab)
	var row
	var rcp_type
	var path
	var parentName
	var childrenRow
	if (location == 'eq'){
		if (index == '0'){
			row = $('#eq_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			if (row.name == 'process'){
				if (row._parentId == undefined){
					$.messager.alert("Tips", "Node cannot be opened.", "info");
					return;
				}
				path = 'process'
				parentName = 'process'
			}else {
			path = getFullPathName(eq_rcp_proc,row.name,row.id)
			parentName = $("#eq_rcp_proc").treegrid('getParent', row.id).name}
			rcp_type = 'process'
			childrenRow = $("#eq_rcp_proc").treegrid('getChildren', row.id)
			unit_type = get_Unit_type(eq_rcp_proc,'process',row)
		}}else if (index == '1'){
			row = $('#eq_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			if (row.name == 'unit'){
				if (row._parentId == undefined){
					$.messager.alert("Tips", "Node cannot be opened.", "info");
					return;
				}
				path = 'unit'
				parentName = 'unit'
			}else {
			path = getFullPathName(eq_rcp_unit,row.name,row.id)
			parentName = $("#eq_rcp_unit").treegrid('getParent', row.id).name}
			rcp_type = 'unit'
			childrenRow = $("#eq_rcp_unit").treegrid('getChildren', row.id)
			unit_type = get_Unit_type(eq_rcp_unit,'unit',row)
		}}else if (index == '2'){
			row = $('#eq_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			if (row.name == 'pump'){
				if (row._parentId == undefined){
					$.messager.alert("Tips", "Node cannot be opened.", "info");
					return;
				}
				path = 'pump'
				parentName = 'pump'
			}
			else {
				path = getFullPathName(eq_rcp_pump,row.name,row.id)
				parentName = $("#eq_rcp_pump").treegrid('getParent', row.id).name
			}
			rcp_type = 'pump'
			childrenRow = $("#eq_rcp_pump").treegrid('getChildren', row.id)
			unit_type = get_Unit_type(eq_rcp_pump,'pump',row)
		}
	}}else {
		if (index == '0'){
			row = $('#server_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			if (row.name == 'process'){
				if (row._parentId == undefined){
					$.messager.alert("Tips", "Node cannot be opened.", "info");
					return;
				}
				path = 'process'
				parentName = 'process'
			}else {
			path = getFullPathName(server_rcp_proc,row.name,row.id)
			parentName = $("#server_rcp_proc").treegrid('getParent', row.id).name}
			rcp_type = 'process'
			childrenRow = $("#server_rcp_proc").treegrid('getChildren', row.id)
			unit_type = get_Unit_type(server_rcp_proc,'process',row)
		}}else if (index == '1'){
			row = $('#server_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			if (row.name == 'unit'){
				if (row._parentId == undefined){
					$.messager.alert("Tips", "Node cannot be opened.", "info");
					return;
				}
				path = 'unit'
				parentName = 'unit'
			}else {
			path = getFullPathName(server_rcp_unit,row.name,row.id)
			parentName = $("#server_rcp_unit").treegrid('getParent', row.id).name}
			rcp_type = 'unit'
			childrenRow = $("#server_rcp_unit").treegrid('getChildren', row.id)
			unit_type = get_Unit_type(server_rcp_unit,'unit',row)
		}}else if (index == '2'){
			row = $('#server_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			if (row.name == 'pump'){
				if (row._parentId == undefined){
					$.messager.alert("Tips", "Node cannot be opened.", "info");
					return;
				}
				path = 'pump'
				parentName = 'pump'
			}
			else {
				path = getFullPathName(server_rcp_pump,row.name,row.id)
				parentName = $("#server_rcp_pump").treegrid('getParent', row.id).name
			}
			rcp_type = 'pump'
			childrenRow = $("#server_rcp_pump").treegrid('getChildren', row.id)
			unit_type = get_Unit_type(server_rcp_pump,'pump',row)
		}
	}
}
	// console.log(row)
	if (!row) {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	if (childrenRow != ''){
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}else {
	var values = (location == 'eq') ? false : true
	var editable = (location == 'server')
	g_cur_ed_rcp_loc = location
	var rcp_fn = row.name
	console.log('######',path)
	var subtype = unit_type

	if (ams_is_sim_mode()) {
		if (rcp_type == 'process') {
			$.getJSON("../recipe_files/process_rcp_01.json", function(json_data){
				open_process_recipe_file(rcp_fn, json_data, editable)
			})
		} else if (rcp_type == 'unit') {
			$.getJSON("../recipe_files/unit_rcp_empty.json", function(json_data){
				// TODO: check user permission
				open_unit_recipe_file(rcp_fn, json_data, editable)
			})
		} else if (rcp_type == 'pump') {
			$.getJSON("../recipe_files/pump_rcp_empty.json", function(json_data){
				open_pump_recipe_file(rcp_fn, json_data, editable)
			})
		}
		// else if (rcp_type == 'unit') {
		// 	$.getJSON("../recipe_files/pump_rcp_empty.json", function(json_data){
		// 		// TODO: check user permission
		// 		open_pump_recipe_file(rcp_fn, json_data, editable)})
	} else {
		set_recipe_group(location, false);
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getRecipeFile"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpName":rcp_fn,
				"rcpType":rcp_type,
				"rcpUnitType":subtype,
				"location":values,
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data) {
               console.log(json_data)
				if (rcp_type == 'process') {
					open_process_recipe_file(rcp_fn, json_data.d==""?"":JSON.parse(json_data.d), editable)
				} else if (rcp_type == 'unit') {
					console.log(JSON.parse(json_data.d))
					open_unit_recipe_file(rcp_fn, JSON.parse(json_data.d), editable)
				} else if (rcp_type == 'pump') {
					console.log(JSON.parse(json_data.d))
					open_pump_recipe_file(rcp_fn, JSON.parse(json_data.d), editable)
				}
			
				
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}}

function on_upload_rcp(msgShow)
{
	if (checkUserLevel() == false){
		return;
	}
	
	// get selected recipe name
	// var row = $('#eq_rcp_grid').datagrid('getSelected')
	var tab = $('#eq_rcp_tabs').tabs('getSelected')
	var index = $('#eq_rcp_tabs').tabs('getTabIndex',tab)
	var row
	var childrenRow
	if (index == '0'){
			row = $('#eq_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			childrenRow = isLeaf(eq_rcp_proc,row.id)
		}}else if (index == '1'){
			row = $('#eq_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			childrenRow = isLeaf(eq_rcp_unit,row.id)
		}}else if (index == '2'){
			row = $('#eq_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			childrenRow = isLeaf(eq_rcp_pump,row.id)
		}}
	if (!row) {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	// console.log(childrenRow)
	if (childrenRow == ''){
		var rcp_fn = row.name;
		if (msgShow == undefined || msgShow == false){
			$.messager.confirm('AMS System',
			'Are you sure to upload "' + rcp_fn + '" to server, files with the same name will be replaced?',
			function(r) {
				if (r)
					__do_upload(row, msgShow)
			});
		}
	else{
		__do_upload(row, msgShow)
	}
	}else {
		// alert(childrenRow == '')
		$.messager.confirm('AMS System',
		'Please select the recipe file to upload.'
		);
	}
}
// var rcp_fn = row.name;
// 		$.messager.confirm('AMS System',
// 		'Are you sure to upload "' + rcp_fn + '" to server, which will replace the file with the same name?',
// 		function(r) {
// 			if (r)
// 				__do_upload(row)
// 		})

function __do_download(fn, eq_array)
{
	// var row = $('#server_rcp_grid').datagrid('getSelected')
	// var rcp_type = $('input:radio[name="rcp_server_type"]:checked').val();
	var tab = $('#server_rcp_tabs').tabs('getSelected')
	var index = $('#server_rcp_tabs').tabs('getTabIndex',tab)
	var row
	var rcp_type
	var path
	var unit_type
	if (index == '0'){
			row = $('#server_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			parentName = $("#server_rcp_proc").treegrid('getParent', row.id).name
			rcp_type = 'process'
			path = getFullPathName(server_rcp_proc,row.name,row.id)
			unit_type = get_Unit_type(eq_rcp_proc,'process',row)
		}}else if (index == '1'){
			row = $('#server_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			parentName = $("#server_rcp_unit").treegrid('getParent', row.id).name
			rcp_type = 'unit'
			path = getFullPathName(server_rcp_unit,row.name,row.id)
			unit_type = get_Unit_type(eq_rcp_unit,'unit',row)
		}}else if (index == '2'){
			row = $('#server_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			parentName = $("#server_rcp_pump").treegrid('getParent', row.id).name
			rcp_type = 'pump'
			path = getFullPathName(server_rcp_pump,row.name,row.id)
			unit_type = get_Unit_type(eq_rcp_pump,'pump',row)
		}}
	var subtype = unit_type
	if (ams_is_sim_mode()) {
		$.messager.alert("Tips", "Download Recipe: " + fn, "info");
	} else {
		if (checkUserLogin() == false)
			return;

		var grp = set_recipe_group(location, true);

		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("downloadRecipe"),
			data:JSON.stringify({
				"rcpName":fn,
				"rcpType":rcp_type,
				"rcpUnitType":subtype,
				"eqNameList":eq_array,
				"userName":"user",
				"creTime":getNowFormatDate(),
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data) {
				//console.log(JSON.parse(json_data.d))
				// add log to server
				var opContext = "Download recipe(" + grp + "/" + path + ") to equipment."
				for (var i = 0; i < eq_array.length; i++)
					add_log_to_server(eq_array[i], "recipe", opContext);
				var result = JSON.parse(json_data.d);
				if(result ==0 ){
          $.messager.alert("Tips", "Download successful.", "info");
          $('#wnd_rcp_download').window('close')
				}else{
					var info = "Cannot download an empty recipe, please choose another one.";
					if (result == -2){
						info = "The equipment is running and cannot be downloaded.";
					}
					$.messager.alert("Tips",info,"info");
					$('#wnd_rcp_download').window('close');
				}
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});	
	}
}

function __do_upload(row, msgShow)
{

	// var rcp_type = $('input:radio[name="rcp_eq_type"]:checked').val();
	var tab = $('#eq_rcp_tabs').tabs('getSelected')
	var index = $('#eq_rcp_tabs').tabs('getTabIndex',tab)
	var rcp_type
	var path
	var parentName
	var unit_type
	var row
	if (index == '0'){
			row = $('#eq_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			parentName = $("#eq_rcp_proc").treegrid('getParent', row.id).name
			unit_type = get_Unit_type(eq_rcp_proc,'process',row)
			rcp_type = 'process'
			path = getFullPathName(eq_rcp_proc,row.name,row.id)
			
		}}else if (index == '1'){
			row = $('#eq_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			parentName = $("#eq_rcp_unit").treegrid('getParent', row.id).name
			unit_type = get_Unit_type(eq_rcp_unit,'unit',row)
			rcp_type = 'unit'
			path = getFullPathName(eq_rcp_unit,row.name,row.id)
		}}else if (index == '2'){
			row = $('#eq_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			parentName = $("#eq_rcp_pump").treegrid('getParent', row.id).name
			unit_type = get_Unit_type(eq_rcp_pump,'pump',row)
			rcp_type = 'pump'
			path = getFullPathName(eq_rcp_pump,row.name,row.id)
		}}
	if (ams_is_sim_mode()) {
		$.messager.alert("Tips", "Upload Recipe: " + row.name, "info");
	} else {
		if (checkUserLogin() == false)
			return;

		set_recipe_group('eq', true);
		
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("uploadRecipe"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpType":rcp_type,
				"rcpUnitType":unit_type,
				"rcpName":row.name,
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data) {
				//console.log(JSON.parse(json_data.d))
				// add log to server
				var opContext = "Upload recipe(" + path + ") to server."
				add_log_to_server(eqn, "recipe", opContext);
				if(JSON.parse(json_data.d) == 0){
					if(msgShow == undefined || msgShow == false)
			    	$.messager.alert("Tips", "Upload successful.", "info");
			    }
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

/*
function on_view_server_rcp()
{
	// get selected recipe name
	var row = $('#server_rcp_grid').datagrid('getSelected');
	if (!row) {
		alert("Select a recipe file please.");
		return;
	}
	var rcp_fn = row.name;
	
	// clear and refill the recipe window
	$.getJSON("../recipe_files/unit_rcp_01.json", function(json_data){
		// TODO: check user permission
		open_unit_recipe_file(rcp_fn, json_data, true)
	});
}
*/

/*
 rcp_loc: eq or server
*/
function on_compare_rcp(rcp_loc)
{	
	var __radio_ctrl_name
	var __grid_name
	if (rcp_loc == 'eq') {
		__radio_ctrl_name = 'eq_rcp_unit'
		__grid_name = '#eq_rcp_tabs'
	} else {
		__radio_ctrl_name = 'server_rcp_unit'
		__grid_name = '#server_rcp_tabs'
	}
	var tab = $(__grid_name).tabs('getSelected')
	var index = $(__grid_name).tabs('getTabIndex',tab)
	var row
	var rcp_type
	var parentName
	var childrenRow
	var unit_type
	if (rcp_loc == 'eq'){
		if (index == '0'){
			row = $('#eq_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			rcp_type = 'process'
			if (row.name == 'process'){
				parentName = 'process'
			}else{
			parentName = $("#eq_rcp_proc").treegrid('getParent', row.id).name}
			childrenRow = $("#eq_rcp_proc").treegrid('getChildren', row.id)
		}}else if (index == '1'){
			row = $('#eq_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			rcp_type = 'unit'
			if (row.name == 'unit'){
				parentName = 'unit'
			}else{
			parentName = $("#eq_rcp_unit").treegrid('getParent', row.id).name}
			childrenRow = $("#eq_rcp_unit").treegrid('getChildren', row.id)
			unit_type = get_Unit_type(eq_rcp_unit,'unit',row)
		}}else if (index == '2'){
			row = $('#eq_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			rcp_type = 'pump'
			if (row.name == 'pump'){
				parentName = 'pump'
			}else{
			parentName = $("#eq_rcp_pump").treegrid('getParent', row.id).name}
			childrenRow = $("#eq_rcp_pump").treegrid('getChildren', row.id)
		}}
	}else {
		if (index == '0'){
			row = $('#server_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			rcp_type = 'process'
			if (row.name == 'process'){
				parentName = 'process'
			}else{
			parentName = $("#server_rcp_proc").treegrid('getParent', row.id).name}
			childrenRow = $("#server_rcp_proc").treegrid('getChildren', row.id)
		}}else if (index == '1'){
			row = $('#server_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			rcp_type = 'unit'
			if (row.name == 'unit'){
				parentName = 'unit'
			}else{
			parentName = $("#server_rcp_unit").treegrid('getParent', row.id).name}
			childrenRow = $("#server_rcp_unit").treegrid('getChildren', row.id)
			unit_type = get_Unit_type(server_rcp_unit,'unit',row)
		}}else if (index == '2'){
			row = $('#server_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			rcp_type = 'pump'
			if (row.name == 'pump'){
				parentName = 'pump'
			}else{
			parentName = $("#server_rcp_pump").treegrid('getParent', row.id).name}
			childrenRow = $("#server_rcp_pump").treegrid('getChildren', row.id)
		}}
	}
	// if (!document.getElementById(__radio_ctrl_name).checked) {
		if (!(rcp_type == 'unit')){
		$.messager.alert("Tips", "Only Unit type recipe can be compared.", "info");
		return
	}

	// get selected recipe name
	// var row = $(__grid_name).datagrid('getSelected')
	
	if (!row) {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	if (childrenRow != ''){
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}else {

	g_cmp_unit_type = unit_type
	g_cmp_eq_1 = get_page_param('eq')
	g_cmp_rcpfn_1 = row.name
	g_cmp_loc_1 = rcp_loc

	$('#rcp_cmp_sel_wnd').window({title:'Select a recipe to compare with:  [' + g_cmp_rcpfn_1 + ']'}).window('open')
	refresh_rcp_cmp_sel_wnd_eq_tree()
	document.getElementById("label_rcp_subtype").innerHTML = g_cmp_unit_type
	document.getElementById("label_rcp_1").innerHTML = get_page_param('eq') + ' / ' + g_cmp_rcpfn_1 + ' [' + rcp_loc + ']'

	$('#switch_cmp_sel_loc').switchbutton({
            checked: (g_cmp_loc_2 == 'eq'),
			onText: 'EQ',
			offText: 'SVR',
            onChange: function(checked){
				var _list_label = ''
				if (checked) {
					g_cmp_loc_2 = 'eq'
					_list_label = 'Recipe (Equipment)'
				} else {
					g_cmp_loc_2 = 'server'
					_list_label = 'Recipe (Server)'
				}
				$('#cmp_unit_rcp_list').treegrid({
					title: _list_label
					})
				
				refresh_rcp_cmp_sel_wnd_rcp_list(get_page_param('eq'))
            }
        })

	var _list_label = ''
	if (g_cmp_loc_2 == 'eq') {		
		_list_label = 'Recipe (Equipment)'
	} else {
		_list_label = 'Recipe (Server)'
	}
	$('#cmp_unit_rcp_list').treegrid({
			title: _list_label
		})
	}}

function on_refresh_rcp_list(location)
{
	var rcp_type = ""
	var __grid_name
	if (location == 'eq') {
		__grid_name = '#eq_rcp_tabs'
	} else {
		__grid_name = '#server_rcp_tabs'
	}
	
	var tab = $(__grid_name).tabs('getSelected')
	var index = $(__grid_name).tabs('getTabIndex',tab)
	switch (index){
		case 0:
			rcp_type = 'process';
			break;
		case 1:
			rcp_type = 'unit';
			break;
		case 2:
			rcp_type = 'pump';
			break;
		default:
			break;
	}

	reload_rcp_list(location, rcp_type)
}

// new 
function reload_rcp_list(location, rcp_type)
{
  eqn = parent.$("#eq_name").val()
	var grid_name = (location == 'eq') ? '#eq_rcp_tabs' : '#server_rcp_tabs'
	var unitName = "";
	if (ams_is_sim_mode()) {
		var jfn = (rcp_type == 'unit') ? 'recipe_list_eq_process_01.json' : 'recipe_list_eq_process_01.json'
		var tab = $(grid_name).tabs('getSelected')
		var index = $(grid_name).tabs('getTabIndex',tab)
		if (location == 'eq'){
			if (index == '0'){
				$("#eq_rcp_proc").treegrid({
					url : 'recipe_list_eq_process_01.json',
					method : 'get',
					idField: 'id',
					treeField: 'name'
				})
			}else if (index == '1'){
				$("#eq_rcp_unit").treegrid({
					url : 'recipe_list_eq_unit_01.json',
					method : 'get',
					idField: 'id',
					treeField: 'name'
				})
			}else if (index == '2'){
				$("#eq_rcp_pump").treegrid({
					url : 'recipe_list_eq_pump_01.json',
					method : 'get',
					idField: 'id',
					treeField: 'name'
			})
		}}else {
			if (index == '0'){
				$("#server_rcp_proc").treegrid({
					url : 'recipe_list_eq_process_01.json',
					method : 'get',
					idField: 'id',
					treeField: 'name'
			})
		}else if (index == '1'){
			$("#server_rcp_unit").treegrid({
				url : 'recipe_list_eq_unit_01.json',
				idField: 'id',
				method : 'get',
				treeField: 'name'
			})}else if (index == '2'){
				$("#server_rcp_pump").treegrid({
					url : 'recipe_list_eq_pump_01.json',
					method : 'get',
					idField: 'id',
					treeField: 'name'
				})
			}}}
		else {
		var eq_location = location
		var loc = (location == 'eq') ? false : true
		set_recipe_group(location, false);

		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEqRecipeList"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpType":rcp_type,
				"unitName":"",
				"location":loc
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				var tab = $(grid_name).tabs('getSelected')
				var index = $(grid_name).tabs('getTabIndex',tab)
				if (eq_location == 'eq'){
					if (index == '0'){
						$("#eq_rcp_proc").treegrid({
							idField : "id",
							treeField : "name",
							data : JSON.parse(json_data.d)

						})
					}else if (index == '1'){
						$("#eq_rcp_unit").treegrid({
							idField : "id",
							treeField : "name",
							data : JSON.parse(json_data.d)
						})
					}else if (index == '2'){
						$("#eq_rcp_pump").treegrid({
							idField : "id",
							treeField : "name",
							data : JSON.parse(json_data.d)
						})
				}}else {
					if (index == '0'){
						$("#server_rcp_proc").treegrid({
							idField : "id",
							treeField : "name",
							data : JSON.parse(json_data.d)
						})
				}else if (index == '1'){
					$("#server_rcp_unit").treegrid({
						idField : "id",
						treeField : "name",
						data : JSON.parse(json_data.d)
					})
				}else if (index == '2'){
					$("#server_rcp_pump").treegrid({
						idField : "id",
						treeField : "name",
						data : JSON.parse(json_data.d)
					})
					}}
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
		// $.post(getWebServiceUrl("getEqRecipeList"),
		// 	{ 'eqName': eqn }, // TODO:
		// 	function(json_data) {
		// 		$(grid_name).datagrid({
		// 			data : json_data.rows
		// 		})
		// 	},
		// 	'json')
		// 	.fail(function(response) {
		// 		alert('Error: ' + response.responseText)
		// 	})

	}
}

function on_rcp_type_switch(location, radioType)
{
	reload_rcp_list(location, radioType.value)
}

// for OK button
function do_new_rcp()
{
	if (checkUserLogin() == false)
		return;

	var grid_name = '#server_rcp_tabs'
	var jfn = (rcp_type == 'unit') ? 'recipe_list_eq_process_01.json' : 'recipe_list_eq_process_01.json'
	var tab = $(grid_name).tabs('getSelected')
	var index = $(grid_name).tabs('getTabIndex',tab)
	var row
	var rcp_type
	var childrenRow
	var path
	var new_rcp_name
	if (index == '0'){
		row = $('#server_rcp_proc').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
			new_rcp_name = document.getElementById('input_new_rcp_name').value
	if (new_rcp_name == '') {
		$.messager.alert("Tips", "Recipe name can\'t be empty.", "info");
		return
	}else{
		childrenRow = isLeaf(server_rcp_proc,row.id)
		if (childrenRow != ''){
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		rcp_type = 'process'
		unit_type = get_Unit_type(server_rcp_proc,rcp_type,row)
		path = getFullPathName(server_rcp_proc,new_rcp_name,row.id)
	}}}}else if (index == '1'){
		row = $('#server_rcp_unit').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		childrenRow = isLeaf(server_rcp_unit,row.id)
		if (childrenRow != ''){
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
			new_rcp_name = document.getElementById('input_new_rcp_name').value
	if (new_rcp_name == '') {
		$.messager.alert("Tips", "Recipe name can\'t be empty.", "info");
		return
	}else{
		rcp_type = 'unit'
		unit_type = get_Unit_type(server_rcp_unit,rcp_type,row)
		path = getFullPathName(server_rcp_unit,new_rcp_name,row.id)
		}}}}else if (index == '2'){
		row = $('#server_rcp_pump').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		childrenRow = isLeaf(server_rcp_pump,row.id)
		if (childrenRow != ''){
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
			 new_rcp_name = document.getElementById('input_new_rcp_name').value
	if (new_rcp_name == '') {
		$.messager.alert("Tips", "Recipe name can\'t be empty.", "info");
		return
	}else{
		rcp_type = 'pump'
		unit_type = get_Unit_type(server_rcp_pump,rcp_type,row)
		path = getFullPathName(server_rcp_pump,new_rcp_name,row.id)
		}}}}
	if (!row) {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	if (childrenRow != ''){
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	document.getElementById("rcp_subtype").innerHTML = unit_type
	var new_rcp_name = document.getElementById('input_new_rcp_name').value
	if (new_rcp_name == '') {
		$.messager.alert("Tips", "Recipe name can\'t be empty.", "info");
		return
	}
	var new_rcp_type = rcp_type
	var new_rcp_subtype = unit_type
	
	//console.log(new_rcp_name)
	//console.log(new_rcp_type)
	//console.log(unit_type)
	//console.log(path)
	// var path = "unit" + '/' + new_rcp_subtype + '/' + new_rcp_name
   
	var rcpUnitType = unit_type
    
  if (ams_is_sim_mode()) {
		
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("newRecipe"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpName":new_rcp_name,
				"rcpType":new_rcp_type,
				"rcpUnitType":rcpUnitType,
				"userName":"user",
				"creTime":getNowFormatDate(),
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data) {
				//console.log(JSON.parse(json_data.d))
				// add log to server
				var opContext = "Upload recipe(" + path + ") to server."
				add_log_to_server(eqn, "recipe", opContext);
				if(JSON.parse(json_data.d) == 0){
					$('#dlg_rcp_new').dialog('close')
					on_refresh_rcp_list('server')
				}else{
					$.messager.alert("Tips", "Create failure.", "info");
				}
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}

	// TODO:
	// 1. call web service
	// 2. check return code and display OK or failed
	// 3. refresh recipe list if OK.
}

function on_rcp_delete()
{
	if (checkUserLevel() == false){
		return;
	}
	
	// get selected recipe name
	// var row = $('#server_rcp_grid').datagrid('getSelected')
	var _grid_name = '#server_rcp_tabs'
	var tab = $(_grid_name).tabs('getSelected')
	var index = $(_grid_name).tabs('getTabIndex',tab)
	var row
	var path
	var childrenRow
	if (index == '0'){
		row = $('#server_rcp_proc').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		path = getFullPathName(server_rcp_proc,row.name,row.id)
		childrenRow = $('#server_rcp_proc').treegrid('getChildren',row.id)
	}}else if (index == '1'){
		row = $('#server_rcp_unit').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		path = getFullPathName(server_rcp_unit,row.name,row.id)
		childrenRow = $('#server_rcp_unit').treegrid('getChildren',row.id)
	}}else if (index == '2'){
		row = $('#server_rcp_pump').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		path = getFullPathName(server_rcp_pump,row.name,row.id)
		childrenRow = $('#server_rcp_pump').treegrid('getChildren',row.id)
	}}
	if (!row) {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	if (childrenRow != ''){
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}else {
	var rcp_fn = row.name

	$.messager.confirm('AMS System',
		'Are you sure to delete "' + rcp_fn + '"?',
		function(r) {
			if (r)
				__do_delete(rcp_fn,path)
		})
	}
}
function __do_delete(fn,path)
{
	if (checkUserLogin() == false)
		return;

	// alert(document.getElementById('radio_rcp_server_unit').checked)
	if (ams_is_sim_mode()) {
		$.messager.alert("Tips", "Delete Recipe: " + path , "info");
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("deleteRecipe"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpName":fn,
				"location":true,
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data) {
				//console.log(JSON.parse(json_data.d))
				// add log to server
				var opContext = "Delete recipe(" + path + ") from server."
				add_log_to_server(eqn, "recipe", opContext);
				if(JSON.parse(json_data.d) == 0){
					$.messager.alert("Tips", "Delete successful.", "info");
					on_refresh_rcp_list('server')
				}else{
					$.messager.alert("Tips", "Delete failed.", "info");
				}
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function on_wnd_btn_download()
{
	var nodes = $('#tree_dl_eq_sel').tree('getChecked')
	if (nodes.length == 0) {
		$.messager.alert('AMS System', 'Select at least one equipment please. ')
		return
	}
	var eqNames = new Array();
	for (var i=0; i<nodes.length; i++) {
		if (nodes[i].type != 'eq') continue
		// if (eqNames != '') eqNames += ','
		eqNames.push(nodes[i].text)
	}
	console.log(eqNames)
	var rcp_fn = document.getElementById('label_dl_rn').innerText
	$.messager.confirm('AMS System',
		'Are you sure to download "' + rcp_fn + '" to:<br />'
		+ eqNames + '?',
		function(r) {
			if (r)
			__do_download(rcp_fn, eqNames)
		})
}

function on_rcp_download()
{
	if (checkUserLevel() == false){
		return;
	}
	
	// get selected recipe name
	// var row = $('#server_rcp_grid').datagrid('getSelected')
	var tab = $('#server_rcp_tabs').tabs('getSelected')
	var index = $('#server_rcp_tabs').tabs('getTabIndex',tab)
	// alert(index)
	var row
	var childrenRow
	if (index == '0'){
			row = $('#server_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			childrenRow = $('#server_rcp_proc').treegrid('getChildren',row.id)
		}}else if (index == '1'){
			row = $('#server_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			childrenRow = $('#server_rcp_unit').treegrid('getChildren',row.id)
		}}else if (index == '2'){
			row = $('#server_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			childrenRow = $('#server_rcp_pump').treegrid('getChildren',row.id)
		}}
	if (!row) {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	var rcp_fn = row.name

	if (childrenRow == ''){

	// open 'Select Equipment' window
	$('#wnd_rcp_download').window('open')

	document.getElementById('label_dl_rn').innerText = rcp_fn
	
	// TODO: extract common part into a function: fill_eq_tree
	set_recipe_group('server', true);

	var tree_data = []
	$.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: getWebServiceUrl("getEqGroupList"),
		data:JSON.stringify({
			
		}),
		dataType: 'json',
		success: function (json_data) {
			console.log(JSON.parse(json_data.d))
			var json_data = JSON.parse(json_data.d)
			for (var i = 0; i < json_data.length; i++) {
				var rootNode = {}
				var grpName = json_data[i]['group_name']
				var grpId = json_data[i]['group_id']
				rootNode['text'] = grpName
				var json_devs = json_data[i]['eq_array']
				var eqNodeArray = []
				for (var k = 0; k < json_devs.length; k++) {
					var eqNode = {}
					eqNode['text'] = json_devs[k]['name']
				//	eqNode['href'] = 'equipment/equipment.html?eq=' + json_devs[k]['name'];
					eqNode['type'] = 'eq'
					eqNodeArray.push(eqNode)
				}
				rootNode['children'] = eqNodeArray
				rootNode['type'] = 'group'
				tree_data.push(rootNode)
			}

			$('#tree_dl_eq_sel').tree({
				data: tree_data
			})
			// Load_GroupList(JSON.parse(json_data.d))
		},
		error: function (response) {
			//alert(errorThrown.message);
			$.messager.alert("Error", "Error: " + response.responseText, "error");
		}
	});
	}else {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
	}
}
function on_rcp_new()
{
	if (checkUserLevel() == false){
		return;
	}
	
	var grid_name = '#server_rcp_tabs'
	var jfn = (rcp_type == 'unit') ? 'recipe_list_eq_process_01.json' : 'recipe_list_eq_process_01.json'
	var tab = $(grid_name).tabs('getSelected')
	var index = $(grid_name).tabs('getTabIndex',tab)
	var row
	var rcp_type
	var childrenRow
	if (index == '0'){
		row = $('#server_rcp_proc').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		childrenRow = isLeaf(server_rcp_proc,row.id)
		if (childrenRow != ''){
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		rcp_type = 'process'
		unit_type = 'process'
	}}}else if (index == '1'){
		row = $('#server_rcp_unit').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		childrenRow = isLeaf(server_rcp_unit,row.id)
		if (childrenRow != ''){
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		rcp_type = 'unit'
		unit_type = 'unit/' + get_Unit_type(server_rcp_unit,rcp_type,row)
		}}}else if (index == '2'){
		row = $('#server_rcp_pump').treegrid('getSelected')
		if (!row) {
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		childrenRow = isLeaf(server_rcp_pump,row.id)
		if (childrenRow != ''){
			$.messager.alert("Tips", "Select a recipe file please.", "info");
			return
		}else {
		rcp_type = 'pump'
		unit_type = 'pump'//get_Unit_type(server_rcp_pump,rcp_type,row)
		}}}
	if (!row) {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	if (childrenRow != ''){
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}
	document.getElementById("rcp_subtype").innerHTML = unit_type
	$('#dlg_rcp_new').dialog('open')

	if (ams_is_sim_mode()) {
		$.getJSON("eq_unit_type_01.json", function(json_data){
		//	console.log(json_data)
			$('#combo_new_crp_unit_type').combobox({
				editable:false,
				data:json_data
			}).combobox('setValue', json_data[0].u)
		})
		$.getJSON("eq_pump_type_01.json", function(json_data){
			//	console.log(json_data)
				$('#combo_new_crp_pump_type').combobox({
					editable:false,
					data:json_data
				}).combobox('setValue', json_data[0].p)
			})
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEqUnitTypeList"),
			data:JSON.stringify({
				"eqName":eqn
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))

				$('#combo_new_crp_unit_type').combobox({
					editable:false,
					data:JSON.parse(json_data.d)
				}).combobox('setValue', JSON.parse(json_data.d)[0].u)
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function row_styler_cmp(index, row)
{
	if (row['diff'] == 1) {
		return 'background-color:#ffffcc'
	} else if (row['diff'] == 2) {
		return 'background-color:#cceeff'
	}
}

function col_fmt_cmp(value, row, index)
{
	if (value[0] == '_') {
		return '<span style="background-color:#ffee00;color:red;">'+ value.substring(1) +'</span>'
	}
	return value
}

function do_view_rcp_cmp_content(json_1, json_2)
{
	var column_array = json_1.columns[0]
	if (column_array[0]['field'] == 'Step_ID')
		column_array.shift()
	for (var i = 0; i < column_array.length; i++) {
		column_array[i]['title'] = column_array[i]['title'].replace(/\s/g, "<br>")
		column_array[i]['align'] = 'center'
		column_array[i]['styler'] = row_styler_cmp
		column_array[i]['formatter'] = col_fmt_cmp
	}

	var column_array = json_2.columns[0]
	if (column_array[0]['field'] == 'Step_ID')
		column_array.shift()
	for (var i = 0; i < column_array.length; i++) {
		column_array[i]['title'] = column_array[i]['title'].replace(/\s/g, "<br>")
		column_array[i]['align'] = 'center'
		column_array[i]['styler'] = row_styler_cmp
		column_array[i]['formatter'] = col_fmt_cmp
	}

	// compare and mark cells
	var min_row_count = Math.min(json_1.rows.length, json_2.rows.length)
	for (var k = 0; k < min_row_count; k++) {
		for (var c = 0; c < json_1.columns[0].length; c++) {
			var col_name = json_1.columns[0][c]['field']
			if (json_1.rows[k][col_name] != json_2.rows[k][col_name]) {
				json_1.rows[k]['diff'] = 1
				json_2.rows[k]['diff'] = 1
				json_1.rows[k][col_name] = '_' + json_1.rows[k][col_name]
				json_2.rows[k][col_name] = '_' + json_2.rows[k][col_name]
			}
		}
	}
	var json_long
	if (json_1.rows.length > json_2.rows.length) {
		json_long = json_1
	} else if (json_1.rows.length < json_2.rows.length) {
		json_long = json_2
	}

	if (json_long) {
		for (var _row = min_row_count; _row < json_long.rows.length; _row++) {
			json_long.rows[_row]['diff'] = 2 // more rows
		}
	}

	$('#grid_rcp_cmp_1').datagrid({
			rownumbers:'true',
			singleSelect:'true',
			lines:true,
			clickToEdit: false,
			dblclickToEdit: false,
			loadMsg: 'Loading Data ......',
			columns:json_1.columns
		});
    if(json_1.rows.length>0){
		$('#grid_rcp_cmp_1').datagrid({
			data:json_1.rows
		});
    }else{
    	$('#grid_rcp_cmp_1').datagrid('loadData',{rows:[]})
    }
    $('#grid_rcp_cmp_2').datagrid({
			rownumbers:'true',
			singleSelect:'true',
			lines:true,
			clickToEdit: false,
			dblclickToEdit: false,
			loadMsg: 'Loading Data ......',
			columns:json_2.columns
		});
	if(json_2.rows.length>0){
   		$('#grid_rcp_cmp_2').datagrid({
			data:json_2.rows
		});
	}else{
		$('#grid_rcp_cmp_2').datagrid('loadData',{rows:[]})
	}
}
function open_process_recipe_file(rcp_filename, json_rcp_content, editable)
{
	g_cur_eq_unit_list = []
	var json_str = JSON.stringify(json_rcp_content)
	json_str = json_str.replace(/</g, LAB)
	json_str = json_str.replace(/>/g, RAB)
	json_rcp_content = JSON.parse(json_str)

	if (editable)
		document.getElementById('proc_rcp_edit_btns').style.display = 'block'
	else
		document.getElementById('proc_rcp_edit_btns').style.display = 'none'

	// show recipe window
	$('#window_proc_rcp').window({title:'Recipe:   [' + rcp_filename + ']'}).window('open')

	// $('#table_proc_rcp').datagrid({
	// 	rownumbers:'true',
	// 	singleSelect:'true',
	// 	lines:true,
	// 	clickToEdit: true,
	// 	dblclickToEdit: editable,
	// 	onDblClickCell: on_edit_proc_rcp_value,
	// 	onSelect: on_edit_prcp_sel_row,
		
	// 	/* function(index,field,value){
	// 		alert(index + ', ' + field + ', ' + value)
	// 	//	if (field == 'val') {
	// 	//		on_edit_config_value()
	// 	//	}
	// 	},*/
	// 	loadMsg: 'Loading Data ......',
	// 	data:json_rcp_content.rows
	// })

	$('#table_proc_rcp').datagrid({
		rownumbers:'true',
		singleSelect:'true',
		lines:true,
		dblclickToEdit: editable,
		onDblClickCell: __do_ed_prop_edit_cell,
		onSelectCell:on_edit_prcp_sel_cell,
		onRowContextMenu: function(e, index, row) {
			var td = $(e.target).closest('td[field]')
			var field = td.attr('field')
			g_prcp_sel_index = index
			g_prcp_sel_field = field
			e.preventDefault()
			$('#prcp_tbl_ctx_menu').menu('show', {
				left:e.pageX,
				top:e.pageY
			})
		},
		onClickRow:function(index, data){
			g_prcp_sel_index = index
		},
		loadMsg: 'Loading Data ......',
		data:json_rcp_content.rows
		})
	if(json_rcp_content==''){
		$('#table_proc_rcp').datagrid('loadData',{rows:[]})
	}
	// $('#table_proc_rcp').datagrid('enableCellSelecting')
}

function __delete_cell(index, field)
{
	var cur_row = $('#table_proc_rcp').datagrid('getRows')[index]
	var cur_col = parseInt(field.substr(1))
	var cur_field = field
	do {
		cur_row[cur_field] = ''
		cur_col++
		if (cur_col < 20) {
			var next_field = 'u' + cur_col
			cur_row[cur_field] = cur_row[next_field]
			cur_field = next_field
		}
	} while (cur_col <= 20)

//	$('#table_unit_rcp').datagrid('getRows')[g_curSelIndex][g_curSelField] = val
//	console.log($('#table_unit_rcp').datagrid('getRows')[g_curSelIndex])
	$('#table_proc_rcp').datagrid('refreshRow', index)
}

function on_ed_prcp_remove_cell()
{
	console.log(g_prcp_sel_index + ', ' + g_prcp_sel_field)
	__delete_cell(g_prcp_sel_index, g_prcp_sel_field)
}

function on_edit_prcp_sel_cell(index, field)
{
	g_prcp_sel_index = index
}

function on_ed_prcp_edit_cell()
{
	__do_ed_prop_edit_cell(g_prcp_sel_index, g_prcp_sel_field)
}

function __do_ed_prop_edit_cell(index, field)
{
	if (g_cur_ed_rcp_loc != 'server') {
		return
	}

	// check is this is the first empty cell in the row,
	// if not, value can't be edit
	var rows = $('#table_proc_rcp').datagrid('getRows')
	var rcpRow = $('#server_rcp_proc').treegrid('getSelected')

	var col_index = parseInt(field.substr(1))
	var prev_field = 'u' + (col_index - 1)
	var prev_val = rows[index][prev_field]
	if ((col_index > 1) && (!prev_val || prev_val == '')) {
		return
	}

	g_prcp_sel_index = index
	g_prcp_sel_field = field

	$('#proc_rcp_value_dlg').dialog('open')

	// fill equipment unit list
	// g_cur_eq_unit_list
	if (ams_is_sim_mode()) {
		if (g_cur_eq_unit_list.length == 0) {
			$.getJSON('eq_overview_01.json', function(json_data){
				var eqArray = json_data['eq_unit_array']
				for (var i = 0; i < eqArray.length; i++) {
				//	console.log(eqArray[i])
					if (eqArray[i].type != 'bm' &&
					eqArray[i].type != 'tm' &&
					eqArray[i].type != 'img') {
						var _row = {}
						_row['name'] = eqArray[i].name
						_row['val'] = eqArray[i].type
						g_cur_eq_unit_list.push(_row)
					}
				}
				$('#ed_prcp_eq_unit_list').datalist('loadData',[])
				$('#ed_prcp_eq_unit_list').datalist({
					data:g_cur_eq_unit_list,
					textField:'name',
					valueField:'val'
				})
			})
		}
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEqUnitInfo"),
			data:JSON.stringify({
				"eqName":eqn,
				"unitName":""
				//"unitName":rcpRow.name
			}),
			dataType: 'json',
			success: function (json_data) {
				//console.log(JSON.parse(json_data.d))
				if (g_cur_eq_unit_list.length == 0) {
					var temp_eq_unit_list = []
					var temp_eq_unit_name_list = []
					var eqArray = JSON.parse(json_data.d)['eq_unit_array']
					for (var i = 0; i < eqArray.length; i++) {
					//	console.log(eqArray[i])
						if (eqArray[i].type != 'bm' &&
						eqArray[i].type != 'tm' &&
						eqArray[i].type != 'img' && 
						eqArray[i].type != undefined) {
							var _row = {}
							_row['name'] = eqArray[i].name
							_row['val'] = eqArray[i].type
							//g_cur_eq_unit_list.push(_row)
							temp_eq_unit_list.push(_row)
							temp_eq_unit_name_list.push(_row['name'])
						}
					}
					// 2019-06-26 10:48, jxb
					temp_eq_unit_name_list.sort();
					for (var j = 0; j < temp_eq_unit_name_list.length; j++)
					{
						for (var k = 0; k < temp_eq_unit_list.length; k++)
						{
							if (temp_eq_unit_name_list[j] == temp_eq_unit_list[k].name)
							{
								g_cur_eq_unit_list.push(temp_eq_unit_list[k]);
								break;
							}
						}
					}
					$('#ed_prcp_eq_unit_list').datalist('loadData',[])
					$('#ed_prcp_eq_unit_list').datalist({
						data:g_cur_eq_unit_list,
						textField:'name',
						valueField:'val'
					})
				}
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function __urcp_fill_header()
{
	//  id="urcp_hn_1" 
	if (g_cur_urcp['HEAD'] != undefined)
	{
			for (var i = 1; i <= g_cur_urcp['HEAD'].length; i++) {
			document.getElementById('urcp_hn_' + i).innerText = g_cur_urcp['HEAD'][i-1].disname
			document.getElementById('urcp_hn_' + i).style.display = ''
			document.getElementById('urcp_hv_' + i).style.display = 'block'
			document.getElementById('urcp_hv_' + i).innerHTML = 
				(g_cur_urcp['HEAD'][i-1].value == undefined || g_cur_urcp['HEAD'][i-1].value == '') ? '&nbsp' : g_cur_urcp['HEAD'][i-1].value
		}
			for (var i = 1; i <= g_cur_urcp['INFO'].length; i++){
				document.getElementById('urcp_in_' + i).innerText = g_cur_urcp['INFO'][i-1].name
				document.getElementById('urcp_iv_' + i).innerText = g_cur_urcp['INFO'][i-1].value
			}
		for (var i = g_cur_urcp['HEAD'].length + 1; i <= 6; i++) {
			document.getElementById('urcp_hv_' + i).style.display = 'none'
			document.getElementById('urcp_hn_' + i).style.display = 'none'
		}
	}
}
/*
 * Open the editor/viewer window to display the recipe content.
 */
function open_unit_recipe_file(rcp_filename, json_rcp_content, editable)
{
	if (editable)
		document.getElementById('rcp_edit_btns').style.display = 'block'
	else
		document.getElementById('rcp_edit_btns').style.display = 'none'
	
	reset_cur_urcp_obj()

	if (json_rcp_content.columns == undefined)
	{
		$.messager.alert('Tips', "This recipe does not support editing view.");
		return;
	}
	g_cur_urcp['HEAD'] = json_rcp_content.header
	g_cur_urcp['INFO'] = json_rcp_content.info
	var column_array = json_rcp_content.columns[0]

	if (column_array[0]['field'] == 'Step_ID')
		column_array.shift()
	g_cur_urcp['COLS'] = column_array
	for (var i = 0; i < column_array.length; i++) {
		column_array[i]['title'] = column_array[i]['title'].replace(/\s/g, "<br>")
		column_array[i]['align'] = 'center'
		if (column_array[i]['type'] == "int") {
			if ('enum' in column_array[i]) {
				// do nothing
			} else if (editable) {
				column_array[i]['editor'] = 'numberbox'
			}
		} else if (editable && (column_array[i]['type'] == "float")) {
		//	var edt_props = {"type":"numberbox", "options":{"precision":2}};
		//	column_array[i]["editor"] = edt_props;
			column_array[i]['editor'] = 'text'
		}
	}


	// show recipe window
	$('#window_unit_rcp').window({title:'Recipe:   [' + rcp_filename + ']'}).window('open')

	// fill header
	__urcp_fill_header()

	// fill rows
	if(!json_rcp_content.rows.length>0){
		$('#table_unit_rcp').datagrid({
			rownumbers:'true',
			singleSelect:'true',
			lines:true,
			clickToEdit: false,
			dblclickToEdit: editable,
			loadMsg: 'Loading Data ......',
			columns:json_rcp_content.columns
		})
		$('#table_unit_rcp').datagrid('loadData',{rows:[]})
	}else{
		$('#table_unit_rcp').datagrid({
			rownumbers:'true',
			singleSelect:'true',
			lines:true,
			clickToEdit: false,
			dblclickToEdit: editable,
			loadMsg: 'Loading Data ......',
			columns:json_rcp_content.columns,
			data:json_rcp_content.rows
		})
	}
}
function open_pump_recipe_file(rcp_filename, json_rcp_content, editable)
{
	if (editable)
		document.getElementById('purcp_edit_btns').style.display = 'block'
	else
		document.getElementById('purcp_edit_btns').style.display = 'none'
	reset_cur_urcp_obj()

	if (json_rcp_content.columns == undefined)
	{
		$.messager.alert('Tips', "This recipe does not support editing view.");
		return;
	}
	var column_array = json_rcp_content.columns[0]

	if (column_array[0]['field'] == 'Step_ID')
		column_array.shift()
	g_cur_urcp['COLS'] = column_array
	for (var i = 0; i < column_array.length; i++) {
		column_array[i]['title'] = column_array[i]['title'].replace(/\s/g, "<br>")
		column_array[i]['align'] = 'center'
		if (column_array[i]['type'] == "int") {
			if ('enum' in column_array[i]) {
				// do nothing
			} else if (editable) {
				column_array[i]['editor'] = 'numberbox'
			}
		} else if (editable && (column_array[i]['type'] == "float")) {
		//	var edt_props = {"type":"numberbox", "options":{"precision":2}};
		//	column_array[i]["editor"] = edt_props;
			column_array[i]['editor'] = 'text'
		}
	}


	// show recipe window
	$('#window_pump_rcp').window({title:'Recipe:   [' + rcp_filename + ']'}).window('open')

	// fill header
	__urcp_fill_header()

	// fill rows
	if(!json_rcp_content.rows.length>0){
		$('#table_pump_rcp').datagrid({
			rownumbers:'true',
			singleSelect:'true',
			lines:true,
			clickToEdit: false,
			dblclickToEdit: editable,
			onDblClickCell:__do_ed_pump_edit_cell,
			loadMsg: 'Loading Data ......',
			columns:json_rcp_content.columns
		})
		$('#table_pump_rcp').datagrid('loadData',{rows:[]})
	}else{
		$('#table_pump_rcp').datagrid({
			rownumbers:'true',
			singleSelect:'true',
			lines:true,
			clickToEdit: false,
			dblclickToEdit: editable,
			onDblClickCell:__do_ed_pump_edit_cell,
			loadMsg: 'Loading Data ......',
			columns:json_rcp_content.columns,
			data:json_rcp_content.rows
		})
	}
}

function __do_ed_pump_edit_cell(index, field){
	if (g_cur_ed_rcp_loc != 'server') {
		return
	}
	var vCur = $('#table_pump_rcp').datagrid('getRows')[index][field]
	var col = $('#table_pump_rcp').datagrid('getColumnOption', field)
	if ("enum" in col) {
		g_curSelIndex = index
		g_curSelField = field
		$('#pump_value_dlg').window('open')
		var val_array = col["enum"].split("|")
		$('#pump_val_list').datalist('loadData',[])
		for (var k = 0; k < val_array.length; k++) {
			$('#pump_val_list').datalist('appendRow',{
					value:val_array[k],
					text:val_array[k]
				})
			if (vCur == val_array[k]) {
				$('#pump_val_list').datalist('selectRow',k)
			}
		}
		return
	}
	var editIndex = index
	if (editIndex != undefined){
		if ($('#table_pump_rcp').datagrid('validateRow', editIndex)){
			$('#table_pump_rcp').datagrid('endEdit', editIndex)
			editIndex = undefined
		} else {
			return
		}
	}
	$('#table_pump_rcp').datagrid('selectRow', index).datagrid('editCell', {
		index: index,
		field: field
	})
	
	editIndex = index

}

function do_rcp_copy()
{
	if (checkUserLevel() == false){
		return;
	}
			
	var node = $('#grp_eq_tree_01').tree('getSelected')
	if($('#grp_eq_tree_01').tree('isLeaf',node.target))
	{
		copy_eqn1 = parent.$("#eq_name").val()
    if(ams_is_sim_mode()){
			$.messager.alert("Tips", "Copy Recipe To: " + copy_path_2, "info");
		}else{
				$.ajax({
					type: 'POST',
					contentType: 'application/json',
					url: getWebServiceUrl("duplicateRecipe"),
					data:JSON.stringify({
						"eqNameSrc":copy_eqn1,
						"rcpPathSrc":copy_path_1,
						"eqNameDst":g_copy_eq_2,
						"rcpPathDst":copy_path_2,
						"bOverwrite":false
					}),
					dataType: 'json',
					success: function (json_data1) {
						// add log to server
						var opContext = "Copy recipe from [" + copy_path_1+  "] to [" + copy_path_2 + json_data1.d + "].";
						add_log_to_server(g_copy_eq_2, "recipe", opContext);
						$.messager.alert("Tips", "The recipe is copied successfully and the new recipe name is '" + json_data1.d + "'.");
			}
		})
		}
	}
	else
	{
		$.messager.alert("Please select the target device to copy.");
	}
}

function do_rcp_cmp()
{	var rcp_2 = ''
	rcp_2 = document.getElementById('label_rcp_2').innerText
	if (rcp_2 == '') {
		$.messager.alert("Tips","Select the second recipe please.", "info");
		return
	}
	$('#rcp_cmp_sel_wnd').window('close')

	$('#rcp_cmp_window').window({maximized: true}).window('open')
	var __t = g_cmp_eq_1 + ' / ' + g_cmp_rcpfn_1 + ' [' + g_cmp_loc_1 + ']'
	$('#layout_rcp_cmp').layout('panel', 'west').panel('setTitle', __t)
	var __t = g_cmp_eq_2 + ' / ' + g_cmp_rcpfn_2 + ' [' + g_cmp_loc_2 + ']'
	$('#layout_rcp_cmp').layout('panel', 'center').panel('setTitle', __t)
    
	var rows = '';
	var path = '';
	var subtype1 = '';
	if(g_cmp_loc_1 == 'eq'){
		rows = $('#eq_rcp_unit').treegrid('getSelected')
		parentName = $("#eq_rcp_unit").treegrid('getParent', rows.id).name
		path = getFullPathName(eq_rcp_unit,rows.name,rows.id)
		unit_type = get_Unit_type(eq_rcp_unit,'unit',rows)
	}else{
		rows = $('#server_rcp_unit').treegrid('getSelected')
		parentName = $("#server_rcp_unit").treegrid('getParent', rows.id).name
		path = getFullPathName(server_rcp_unit,rows.name,rows.id)
		unit_type = get_Unit_type(server_rcp_unit,'unit',rows)
	}
	var comRow = $('#cmp_unit_rcp_list').treegrid('getSelected')
	var path2 = getFullPathName(cmp_unit_rcp_list,comRow.name,comRow.id)
	var subtype2 = get_Unit_type(cmp_unit_rcp_list,'unit',comRow)
	subtype1 = unit_type

    if(ams_is_sim_mode()){
		$.getJSON("../recipe_files/unit_rcp_01.json", function(json_data1){
				$.getJSON("../recipe_files/unit_rcp_02.json", function(json_data2){
				do_view_rcp_cmp_content(json_data1, json_data2)
			});
		});
    }else{
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getRecipeFile"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpName":g_cmp_rcpfn_1,
				"rcpType":'unit',
				"rcpUnitType":subtype1,
				"location":(g_cmp_loc_1 == 'eq') ? false : true,
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data1) {
                console.log(JSON.parse(json_data1.d))
                $.ajax({
					type: 'POST',
					contentType: 'application/json',
					url: getWebServiceUrl("getRecipeFile"),
					data:JSON.stringify({
						"eqName":eqn,
						"rcpName":g_cmp_rcpfn_2,
						"rcpType":'unit',
						"rcpUnitType":subtype2,
						"location":(g_cmp_loc_2 == 'eq') ? false : true,
						"rcpPath":path2
					}),
					dataType: 'json',
					success: function (json_data2) {
		               console.log(json_data2)

		               do_view_rcp_cmp_content(JSON.parse(json_data1.d), JSON.parse(json_data2.d))

					},
					error: function (response) {
						$.messager.alert("Error", "Error: " + response.responseText, "error");
					}
				});
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
    }
	
}

function do_rcp_cmp_cancel()
{
	$('#rcp_cmp_sel_wnd').window('close')
}

function setRecipeValue(val)
{
//	alert(g_curSelIndex + ", " +g_curSelField);
	$('#table_unit_rcp').datagrid('getRows')[g_curSelIndex][g_curSelField] = val
	console.log($('#table_unit_rcp').datagrid('getRows')[g_curSelIndex])
	$('#table_unit_rcp').datagrid('refreshRow', g_curSelIndex)
	$('#value_dlg').dialog('close')
}

function setRecipeValue1(val)
{
	$('#table_pump_rcp').datagrid('getRows')[g_curSelIndex][g_curSelField] = val
	console.log($('#table_pump_rcp').datagrid('getRows')[g_curSelIndex])
	$('#table_pump_rcp').datagrid('refreshRow', g_curSelIndex)
	$('#pump_value_dlg').dialog('close')
}

function refresh_rcp_cmp_sel_wnd_eq_tree()
{
	var tree_data = [];
	if (ams_is_sim_mode()) {
		$.getJSON("../group_eq_cfg.json", function(json_data){
			for (var i = 0; i < json_data.length; i++) {
				var rootNode = {}
				var grpName = json_data[i]['group_name']
				var grpId = json_data[i]['group_id']
				rootNode['text'] = grpName
				var json_devs = json_data[i]['eq_array']
				var eqNodeArray = []
				for (var k = 0; k < json_devs.length; k++) {
					var eqNode = {}
					eqNode['text'] = json_devs[k]['name']
				//	eqNode['href'] = 'equipment/equipment.html?eq=' + json_devs[k]['name'];
					eqNode['type'] = 'eq'
					eqNodeArray.push(eqNode)
				}
				rootNode['children'] = eqNodeArray
				rootNode['type'] = 'group'
				tree_data.push(rootNode)
			}

			$('#grp_eq_tree').tree({
				data: tree_data,
				onClick: function(node){
					g_cmp_eq_2 = node.text
					g_cmp_sel_cur_tree_node_type = node.type
					refresh_rcp_cmp_sel_wnd_rcp_list(g_cmp_eq_2)
				}
			})
			$('#grp_eq_tree_01').tree({
				data: tree_data,
				onClick: function(node){
					copy_eqn2 = node.text
					// g_copy_sel_cur_tree_node_type = node.type
					refresh_rcp_copy_sel_wnd_rcp_list(g_copy_eq_2)
				}
			})
			
		})
	}else{
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEqGroupList"),
			data:JSON.stringify({
				
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				for (var i = 0; i < JSON.parse(json_data.d).length; i++) {
					var rootNode = {}
					var grpName = JSON.parse(json_data.d)[i]['group_name']
					var grpId = JSON.parse(json_data.d)[i]['group_id']
					rootNode['text'] = grpName
					var json_devs = JSON.parse(json_data.d)[i]['eq_array']
					var eqNodeArray = []
					for (var k = 0; k < json_devs.length; k++) {
						var eqNode = {}
						eqNode['text'] = json_devs[k]['name']
					//	eqNode['href'] = 'equipment/equipment.html?eq=' + json_devs[k]['name'];
						eqNode['type'] = 'eq'
						eqNodeArray.push(eqNode)
					}
					rootNode['children'] = eqNodeArray
					rootNode['type'] = 'group'
					tree_data.push(rootNode)
				}

				$('#grp_eq_tree').tree({
					data: tree_data,
					onClick: function(node){
						g_cmp_eq_2 = node.text
						g_cmp_sel_cur_tree_node_type = node.type
						refresh_rcp_cmp_sel_wnd_rcp_list(g_cmp_eq_2)
					}
				})

				$('#grp_eq_tree_01').tree({
					data: tree_data,
					onClick: function(node){
						g_copy_eq_2 = node.text
						refresh_rcp_copy_sel_wnd_rcp_list(g_copy_eq_2)	
					}
				})
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
				acquiescent()
			}
		});
	}
	
}

function refresh_rcp_copy_sel_wnd_rcp_list(eqn)
{
	// var eqn = parent.$("#eq_name").val()
	var row = ''
	if (ams_is_sim_mode()) {
		$("#copy_unit_rcp_list").treegrid({
			url : 'recipe_list_eq_unit_02.json',
			idField: 'id',
			treeField: 'name'
		})
		row = $("#copy_unit_rcp_list").treegrid('getSelected')
		if (row == null){

		}else{
		var rcp_fn = row.name
		copy_path_2 = getFullPathName(copy_unit_rcp_list,row.name+'/',row.id)
		alert(copy_path_2)
	}}else{
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEqRecipeList"),
			data:JSON.stringify({
				"eqName":copy_eqn2,
				"rcpType":copy_rcp_type,
				"unitName":copy_unit_type,
				"location":true
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				$('#copy_unit_rcp_list').treegrid({
					idField : "id",
					treeField : "name",
					data : JSON.parse(json_data.d)
				})
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}


function refresh_rcp_cmp_sel_wnd_rcp_list(eqn)
{
	if (g_cmp_sel_cur_tree_node_type != 'eq') {
		return
	}
	var value = (g_cmp_loc_2 == 'eq') ? false : true
	var __rows = ""
	// __url = ".../getEqRecipeList.aspx?eqName=" + eqn + "&rcpType=unit&unitName=" + g_cmp_unit_type + "&location=" + loc;
	if (ams_is_sim_mode()) {
		if (g_cmp_loc_2 == 'eq') {
			$("#cmp_unit_rcp_list").treegrid({
				url : 'recipe_list_eq_unit_02.json',
				idField: 'id',
				treeField: 'name'
		})
		__rows = $("#cmp_unit_rcp_list").treegrid('getSelected')
	 } else if (g_cmp_loc_2 == "server") {
		$("#cmp_unit_rcp_list").treegrid({
			url : 'recipe_list_eq_unit_02.json',
			idField: 'id',
			treeField: 'name'
	})
		}
	}else{
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEqRecipeList"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpType":"unit",
				"unitName":g_cmp_unit_type,
				"location":value
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				$('#cmp_unit_rcp_list').treegrid({
					idField : "id",
					treeField : "name",
					data : JSON.parse(json_data.d)
				})
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function __get_urcp_default_row()
{
	var rowVar = {}
	for (var i = 0; i < g_cur_urcp['COLS'].length; i++) {
		var curCol = g_cur_urcp['COLS'][i]
		if (curCol.enum != undefined) {
			rowVar[curCol.field] = curCol.enum.split('|')[0]
		} else if (curCol.type == 'int' || curCol.type == 'float') {
			rowVar[curCol.field] = 0
		}
	}
	return rowVar
}

function __get_prcp_default_row()
{
	return {}
}

function on_ed_urcp_append()
{
	$('#table_unit_rcp').datagrid('appendRow', __get_urcp_default_row())
}

function on_ed_prcp_append()
{
	$('#table_proc_rcp').datagrid('appendRow', __get_prcp_default_row())
}

function on_ed_urcp_insert()
{
	if (g_ed_urcp_cur_sel_index == undefined) {
		$.messager.alert('AMS System', 'Select a row please. ')
		return
	}
	$('#table_unit_rcp').datagrid('insertRow', {
		index:g_ed_urcp_cur_sel_index, 
		row:__get_urcp_default_row()
	})
//	g_ed_urcp_cur_sel_index = undefined
}

function on_ed_prcp_insert()
{
	if (g_prcp_sel_index == undefined) {
		//$('#table_proc_rcp').datagrid(��selectRow��)
		//var rowIndex=$('#table_proc_rcp').datagrid('getRowIndex',$('#table_proc_rcp').datagrid('getSelected'))
		$.messager.alert('AMS System', 'Select a row please. ')
		return
	}
	$('#table_proc_rcp').datagrid('insertRow', {
		index:g_prcp_sel_index, 
		row:__get_prcp_default_row()
	})
//	g_ed_urcp_cur_sel_index = undefined
}


function on_ed_urcp_save()
{
	if (checkUserLevel() == false){
		return;
	}
	
	var rows = 	$('#table_unit_rcp').datagrid('getRows')
	if (rows.length == 0)
	{
		$.messager.alert("Tips", "Please add at least one step.", "info");
		return;
	}
  var editRow = undefined;
	var json_file = {}
	json_file['info'] = g_cur_urcp['INFO']
	json_file['header'] = g_cur_urcp['HEAD']
	if (json_file['header'].length > 0)
	{
		if(!json_file['header'][0].hasOwnProperty("value")){
			for (var i = 0; i < json_file['header'].length; i++) {
				json_file['header'][i]['value'] = ''
			}
		}
	}
	json_file['columns'] = []
	json_file['columns'].push(g_cur_urcp['COLS'])
	var index = $('#table_unit_rcp').datagrid('getRowIndex',$('#table_unit_rcp').datagrid('getSelected'))
	$('#table_unit_rcp').datagrid('endEdit',index)
	//var rows = 	$('#table_unit_rcp').datagrid('getRows')
	var rcpRow = $('#server_rcp_unit').treegrid('getSelected')
	var parentName = $("#server_rcp_unit").treegrid('getParent', rcpRow.id).name
	var server_rcp_unit = '#server_rcp_unit'
	var path = getFullPathName(server_rcp_unit,rcpRow.name,rcpRow.id)

	// re-index rows step_id
	for (var i = 0; i < rows.length; i++) {
		rows[i]['Step_ID'] = i + 1
	}
	json_file['rows'] = rows
	var json_str = JSON.stringify(json_file)
	// replace < and >
	json_str = json_str.replace(/&lt;/g, '<')
	json_str = json_str.replace(/&gt;/g, '>')
	console.log(JSON.stringify(json_file))
	if (ams_is_sim_mode()) {
		// TODO: write file to AMS server
	}else{
		var userName = GetCookie('ams_user_name');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("updateRecipeFile"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpName":rcpRow.name,
				"rcpType":"unit",
				"rcpUnitType":parentName,
				"userName":userName,
				"creTime":getNowFormatDate(),
				"rcpConten":json_str,
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				if(JSON.parse(json_data.d)==0){
 					$("#window_unit_rcp").window('close')
				}else{
					$.messager.alert("Tips", "Save failed.", "info");
				}
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});


	}
}

function on_ed_purcp_save()
{
	 if (checkUserLogin() == false){
	 	return;
	 }

	var rows = 	$('#table_pump_rcp').datagrid('getRows')
	if (rows.length == 0)
	{
		$.messager.alert("Tips", "Please add at least one step.", "info");
		return;
	}
  var editRow = undefined;
	var json_file = {}
	// json_file['info'] = g_cur_urcp['INFO']
	json_file['header'] = [];//g_cur_urcp['HEAD']
	// if (json_file['header'].length > 0)
	// {
	// 	if(!json_file['header'][0].hasOwnProperty("value")){
	// 		for (var i = 0; i < json_file['header'].length; i++) {
	// 			json_file['header'][i]['value'] = ''
	// 		}
	// 	}
	// }
	json_file['columns'] = []
	json_file['columns'].push(g_cur_urcp['COLS'])
	var index = $('#table_pump_rcp').datagrid('getRowIndex',$('#table_pump_rcp').datagrid('getSelected'))
	$('#table_pump_rcp').datagrid('endEdit',index)
	//var rows = 	$('#table_unit_rcp').datagrid('getRows')
	var rcpRow = $('#server_rcp_pump').treegrid('getSelected')
	var parentName = $("#server_rcp_pump").treegrid('getParent', rcpRow.id).name
	var server_rcp_pump = '#server_rcp_pump'
	var path = getFullPathName(server_rcp_pump,rcpRow.name,rcpRow.id)
	// re-index rows step_id
	for (var i = 0; i < rows.length; i++) {
		rows[i]['Step_ID'] = i + 1
	}
	json_file['rows'] = rows
	var json_str = JSON.stringify(json_file)
	// replace < and >
	json_str = json_str.replace(/&lt;/g, '<')
	json_str = json_str.replace(/&gt;/g, '>')
	console.log(JSON.stringify(json_file))
	if (ams_is_sim_mode()) {
		// TODO: write file to AMS server
	}else{
		var userName = GetCookie('ams_user_name');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("updateRecipeFile"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpName":rcpRow.name,
				"rcpType":"pump",
				"rcpUnitType":parentName,
				"userName":userName,
				"creTime":getNowFormatDate(),
				"rcpConten":json_str,
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				if(JSON.parse(json_data.d)==0){
 					$("#window_pump_rcp").window('close')
				}else{
					$.messager.alert("Tips", "Save failed.", "info");
				}
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});


	}
}

function on_ed_prcp_save()
{
	if (checkUserLevel() == false){
		return;
	}

//	alert('save')
	var json_file = {}
	var rows = 	$('#table_proc_rcp').datagrid('getRows')
	// get selected recipe name
	var rcpRow = $('#server_rcp_proc').treegrid('getSelected')
	parentName = $("#server_rcp_proc").treegrid('getParent', rcpRow.id).name
	path = getFullPathName(server_rcp_proc,rcpRow.name,rcpRow.id)
	json_file['rows'] = rows
	var json_str = JSON.stringify(json_file)
	// replace < and >
	json_str = json_str.replace(/&lt;/g, '<')
	json_str = json_str.replace(/&gt;/g, '>')
	console.log(json_str)
	if (ams_is_sim_mode()) {
		console.log(json_str)
	} else {
		var userName = GetCookie('ams_user_name');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("updateRecipeFile"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpName":rcpRow.name,
				"rcpType":"process",
				"rcpUnitType":"",
				"userName":userName,
				"creTime":getNowFormatDate(),
				"rcpConten":json_str,
				"rcpPath":path
			}),
			dataType: 'json',
			success: function (json_data) {
				//console.log(JSON.parse(json_data.d))
				// add log to server
				var opContext = "Save recipe[" + path+  "] to server.";
				add_log_to_server(eqn, "recipe", opContext);
				if(JSON.parse(json_data.d)==0){
 					$("#window_proc_rcp").window('close')
				}else{
					$.messager.alert("Tips", "Save failed.", "info");
				}
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});

	}
}

function on_ed_urcp_remove_row()
{
	if (g_ed_urcp_cur_sel_index == undefined) {
		$.messager.alert('AMS System', 'Select a row please. ')
		return
	}

//	console.log(g_ed_urcp_cur_sel_index)
	$('#table_unit_rcp').datagrid('deleteRow', g_ed_urcp_cur_sel_index)
	g_ed_urcp_cur_sel_index = undefined
}

function on_ed_prcp_remove_row()
{
	if (g_prcp_sel_index == undefined) {
		$.messager.alert('AMS System', 'Select a row please. ')
		return
	}

//	console.log(g_ed_urcp_cur_sel_index)
	$('#table_proc_rcp').datagrid('deleteRow', g_prcp_sel_index)
	g_prcp_sel_index = undefined
}

function __set_prcp_cell_val(val)
{
	console.log(g_prcp_sel_index + ',' + g_prcp_sel_field)
	$('#table_proc_rcp').datagrid('getRows')[g_prcp_sel_index][g_prcp_sel_field] = val
	$('#table_proc_rcp').datagrid('refreshRow', g_prcp_sel_index)
}

function on_get_item_info(path)
{
	var item = "";
	var arrItem = path.split("/");
	if (arrItem.length > 2)
	{
		for (k = 2; k < arrItem.length; k++)
		{
			item += arrItem[k];
			if (k < arrItem.length - 1)
			{
				item += "\\";
			}
		}
	}
	return item;
}


function on_ed_prcp_set_value()
{
	var __row_unit = $('#ed_prcp_eq_unit_list').datalist('getSelected')
	var __row_urcp = $('#ed_prcp_eq_urcp_list').treegrid('getSelected')

	//$('#proc_rcp_value_dlg').dialog('close')
 	if (!__row_unit || !__row_urcp) {
		$.messager.alert("Tips", "Select a recipe file please.", "info");
		return
	}else{
		// var __new_val = LAB + __row_unit.name + RAB + __row_urcp.name
		var item = on_get_item_info(getFullPathName(ed_prcp_eq_urcp_list,__row_urcp.name,__row_urcp.id));
		var __new_val = LAB + __row_unit.name + RAB + item
		__set_prcp_cell_val(__new_val)

		$('#proc_rcp_value_dlg').dialog('close')
	}
}

function on_ed_prcp_cancelt_value()
{
	$('#proc_rcp_value_dlg').dialog('close');
}

function set_header_value(val)
{
	g_cur_urcp['HEAD'][g_rcpHeaderId - 1].value = val;
	document.getElementById('urcp_hv_' + g_rcpHeaderId).innerHTML = val;
	$('#set_header_value_dlg').dialog('close')
}

// function set_info_value(name,value)
// {
// 	g_cur_urcp['INFO'][g_rcpInfoId - 1].name = name;
// 	g_cur_urcp['INFO'][g_rcpInfoId - 1].value = value;
// 	document.getElementById('urcp_in_' + g_rcpHeaderId).innerHTML = name;
// 	document.getElementById('urcp_iv_' + g_rcpHeaderId).innerHTML = value;
// }

function setRecipeHeaderValue(val)
{
	//$('#urcp_hv_2').linkbutton({ text:'test' });
	var valTemp = val;
	while (valTemp.indexOf('/') > 0){
		valTemp = valTemp.replace("/", "\\");
	}
	g_cur_urcp['HEAD'][g_rcpHeaderId - 1].value = "RECIPE\\Pump\\" + valTemp;
	document.getElementById('urcp_hv_' + g_rcpHeaderId).innerHTML = "RECIPE\\Pump\\" + valTemp;
	$('#rcp_select_dlg').dialog('close')
	//$('#header_value_dlg').dialog('close')
}

var g_head_edit_pump = false;
var g_head_edit_pump_dlg_ok_handler = null;
function on_header_edit(id)
{
	if (g_cur_ed_rcp_loc != 'server') {
		return
	}
	
	g_rcpHeaderId = id;
	var vCurName = (g_cur_urcp['HEAD'][id-1].disname);
	if (vCurName == "PR_RECIPE" || vCurName == "PR Recipe")
	{
		var vCurVal = (g_cur_urcp['HEAD'][id-1].value);
		var val_array;
		if (vCurVal != undefined)
		{
			val_array = vCurVal.split("\\");
		}
		
		g_head_edit_pump = true;
		g_head_edit_pump_dlg_ok_handler = function(val) {
			setRecipeHeaderValue(val);
			g_head_edit_pump = false;
		}
		$('#rcp_select_dlg').window('open')
		__rcp_dummy_enum_rcp('pump')
/*
		$('#header_value_dlg').window('open')
		if (ams_is_sim_mode()) {alert('xxx')
		} else {
				$.ajax({
					type: 'POST',
					contentType: 'application/json',
					url: getWebServiceUrl("getEqRecipeList"),
					data:JSON.stringify({
						"eqName":eqn,
						"rcpType":'pump',
						"unitName":vCurName,
						"location":vCurVal
					}),
					dataType: 'json',
					success: function (json_data) {
						console.log(JSON.parse(json_data.d))
						var rcp_array = JSON.parse(json_data.d);
						for (var k = 0; k < rcp_array.length; k++)
						{
							$('#header_val_list').datalist('appendRow',{
							value:rcp_array[k].name,
							text:rcp_array[k].name
							})
							if (vCurVal != undefined && val_array[2] == rcp_array[k].name) {
								$('#header_val_list').datalist('selectRow',k)
							}
						}
						if(vCurVal == undefined)
						{
							$('#header_val_list').datalist('selectRow',0)
						}
					},
					error: function (response) {
						$.messager.alert("Error", "Error: " + response.responseText, "error");
					}
				});
			}*/
	}
	else
	{
			$('#set_header_value_dlg').window('open')
			document.getElementById('header_var_name').innerHTML = g_cur_urcp['HEAD'][id-1].disname
			$('#input_cv').textbox('setText', g_cur_urcp['HEAD'][id-1].value)
			$('#input_nv').textbox('setText', '')
	}
}

function on_header_edit_1()
{
	on_header_edit(1);
}

function on_header_edit_2()
{
	on_header_edit(2);
}

function on_header_edit_3()
{
	on_header_edit(3);
}

function on_header_edit_4()
{
	on_header_edit(4);
}

function on_header_edit_5()
{
	on_header_edit(5);
}

function on_header_edit_6()
{
	on_header_edit(6);
}

function getFullPathName(_grid_name,name,id)
{
	var pathName = ""
	var parentRow = $(_grid_name).treegrid('getParent', id)
	while (parentRow != null)
	{
		pathName = parentRow.name + '/' + pathName
		parentRow = $(_grid_name).treegrid('getParent', parentRow.id)
	}
	pathName = pathName + name
	return pathName
}

function isLeaf(_grid_name,id)
{
	var childrenRow = ''
	childrenRow = $(_grid_name).treegrid('getChildren',id)
	// childrenRow = (childrenRow == null)?true:false
	return childrenRow
}

function load_rcp_list(location, rcp_type){
	eqn = parent.$("#eq_name").val()
	var type = rcp_type
	var tree_data = []
	var childrenRow = ''
	if (ams_is_sim_mode()) {
		if (location == 'eq'){
			if (type == 'process'){
				$("#eq_rcp_proc").treegrid({
					url : 'recipe_list_eq_process_01.json',
					idField: 'id',
					treeField: 'name'
				})
			}else if (type == 'unit'){
				$("#eq_rcp_unit").treegrid({
					url : 'recipe_list_eq_unit_01.json',
					idField: 'id',
					treeField: 'name'
				})
			}else if (type == 'pump'){
				$("#eq_rcp_pump").treegrid({
					url : 'recipe_list_eq_pump_01.json',
					idField: 'id',
					treeField: 'name'
				})
			}
		}else if (location == 'server'){
			if (type == 'process'){
				$("#server_rcp_proc").treegrid({
					url : 'recipe_list_eq_process_01.json',
					onContextMenu: function(e,row){
						childrenRow = isLeaf(server_rcp_proc,row.id)
						old_name = row.name
						rename_type = 'process'
						rename_unit_type = ''
						rename_path = getFullPathName(server_rcp_proc,row.name,row.id)
						e.preventDefault()
						$(this).treegrid('select', row.id) //选中当前行
						if (childrenRow != ''){
							
						}else{
    					$('#server_file_context_menu').menu('show', {
       					left: e.pageX,
        				top: e.pageY
    					})
					}},
					idField: 'id',
					treeField: 'name'
				})
			}else if (type == 'unit'){
				$("#server_rcp_unit").treegrid({
					url : 'recipe_list_eq_unit_01.json',
					onContextMenu: function(e,row){
						childrenRow = isLeaf(server_rcp_unit,row.id)
						old_name = row.name
						rename_type = 'unit'
						rename_unit_type = get_Unit_type(server_rcp_unit,'unit',row)
						rename_path = getFullPathName(server_rcp_unit,row.name,row.id)
						e.preventDefault()
						$(this).treegrid('select', row.id) //选中当前行
						if (childrenRow != ''){
							
						}else{
    					$('#server_file_context_menu').menu('show', {
       					left: e.pageX,
        				top: e.pageY
    					})
					}},
					idField: 'id',
					treeField: 'name'
				})
			}else if (type == 'pump'){
				$("#server_rcp_pump").treegrid({
					url : 'recipe_list_eq_pump_01.json',
					onContextMenu: function(e,row){
						childrenRow = isLeaf(server_rcp_pump,row.id)
						old_name = row.name
						rename_type = 'pump'
						rename_unit_type = get_Unit_type(server_rcp_pump,'pump',row)
						rename_path = getFullPathName(server_rcp_pump,row.name,row.id)
						e.preventDefault()
						$(this).treegrid('select', row.id) //选中当前行
						if (childrenRow != ''){
							
						}else{
    					$('#server_file_context_menu').menu('show', {
       					left: e.pageX,
        				top: e.pageY
    					})
					}},
					idField: 'id',
					treeField: 'name'
				})
			}
		}
	}
	else {
	var eq_location = location
	var type = rcp_type
	var location = (location == 'eq') ? false : true
	var treeRoots=$("#server_rcp_proc").treegrid('getRoots');
	$.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: getWebServiceUrl("getEqRecipeList"),
		//async:false,
		data:JSON.stringify({
			"eqName":eqn,
			"rcpType":rcp_type,
			"unitName":"",
			"location":location
		}),
		dataType: 'json',
		success: function (json_data) {
			console.log(JSON.parse(json_data.d))
			var type = rcp_type
			if (eq_location == 'eq'){
				if (type == 'process'){
					$("#eq_rcp_proc").treegrid({
						idField : "id",
						treeField : "name",
						onContextMenu: function(e,row){
							e.preventDefault()
							$(this).treegrid('select', row.id)
							$('#eq_file_context_menu').menu('show', {
							  left: e.pageX,
								top: e.pageY
							})
						},
						data : JSON.parse(json_data.d)
					})
				}else if (type == 'unit'){
					$("#eq_rcp_unit").treegrid({
						idField : "id",
						treeField : "name",
						onContextMenu: function(e,row){
							e.preventDefault()
							$(this).treegrid('select', row.id)
							$('#eq_file_context_menu').menu('show', {
							  left: e.pageX,
								top: e.pageY
							})
						},
						data : JSON.parse(json_data.d)
					})
				}else if (type == 'pump'){
					$("#eq_rcp_pump").treegrid({
						idField : "id",
						treeField : "name",
						onContextMenu: function(e,row){
							e.preventDefault()
							$(this).treegrid('select', row.id)
							$('#eq_file_context_menu').menu('show', {
							  left: e.pageX,
								top: e.pageY
							})
						},
						data : JSON.parse(json_data.d)
					})
			}}else {
				if (type == 'process'){
					//var treeRoots=$("#server_rcp_proc").treegrid('getRoots');
					$("#server_rcp_proc").treegrid({
						idField : "id",
						treeField : "name",
						onContextMenu: function(e,row){
							childrenRow = isLeaf(server_rcp_proc,row.id)
							old_name = row.name
							rename_type = 'process'
							rename_unit_type = ''
							rename_path = getFullPathName(server_rcp_proc,row.name,row.id)
							e.preventDefault()
							$(this).treegrid('select', row.id) //选中当前行
							if (childrenRow != ''){
								
							}else{
							$('#server_file_context_menu').menu('show', {
							   left: e.pageX,
							top: e.pageY
							})
						}},
						data : JSON.parse(json_data.d)
					})
					//var treeRoots=$("#server_rcp_proc").treegrid('getRoots');
					//$("#server_rcp_proc").treegrid('reload');
					//var ttt = "test";
			}else if (type == 'unit'){
				$("#server_rcp_unit").treegrid({
					idField : "id",
					treeField : "name",
					onContextMenu: function(e,row){
						childrenRow = isLeaf(server_rcp_unit,row.id)
						old_name = row.name
						rename_type = 'unit'
						rename_unit_type = get_Unit_type(server_rcp_unit,'unit',row)
						rename_path = getFullPathName(server_rcp_unit,row.name,row.id)
						e.preventDefault()
						$(this).treegrid('select', row.id) //选中当前行
						if (childrenRow != ''){
							
						}else{
						$('#server_file_context_menu').menu('show', {
						   left: e.pageX,
						top: e.pageY
						})
					}},
					data : JSON.parse(json_data.d)
				})
			}else if (type == 'pump'){
				$("#server_rcp_pump").treegrid({
					idField : "id",
					treeField : "name",
					onContextMenu: function(e,row){
						childrenRow = isLeaf(server_rcp_pump,row.id)
						old_name = row.name
						rename_type = 'pump'
						rename_unit_type = get_Unit_type(server_rcp_pump,'pump',row)
						rename_path = getFullPathName(server_rcp_pump,row.name,row.id)
						e.preventDefault()
						$(this).treegrid('select', row.id) //选中当前行
						if (childrenRow != ''){
							
						}else{
						$('#server_file_context_menu').menu('show', {
						   left: e.pageX,
						top: e.pageY
						})
					}},
					data : JSON.parse(json_data.d)
				})
				}}},
		error: function (response) {
			$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		})
	}
}

// 20190613 start
var g_current_dummy_cnt = null
function on_dummy_rcp(rcp_loc)
{
	// load dummy recipe list
	__rcp_dummy_load_list()
	__rcp_dummy_clear_canvas()

	$('#window_dummy').window({title:'Dummy Recipe'}).window('open')
}

function __rcp_dummy_clear_canvas()
{
	var the_canvas = document.getElementById('rcp_dummy_canvas')
	var ctx = the_canvas.getContext("2d")
	ctx.clearRect(0, 0, the_canvas.width, the_canvas.height)
}

function __rcp_dummy_fill_list(jdata)
{
	if (jdata == null) {
		alert('can\'t get dummy recipe list.')
		return
	}

	$('#rcp_dummy_list').datalist({
		data:jdata,
		textField:'name',
		valueField:'name'
	})
	
	if (g_rowSelPre != null)
	{
			$('#rcp_dummy_list').datagrid('selectRow', g_rowSelPre.id - 2); 
	}
	else
	{
		if (jdata.length > 0)
			$('#rcp_dummy_list').datagrid('selectRow', 0); 
	}
}

function __rcp_dummy_load_list()
{
	// clear old content
	g_rowSelPre = $('#rcp_dummy_list').datalist('getSelected');
	$("#rcp_dummy_list").datalist('loadData',[])

	// get list
	if (ams_is_sim_mode()) {
		var sample_filename = 'recipe_list_eq_dummy_01.json'
		$.getJSON(sample_filename, 
		function(json_data) {
			__rcp_dummy_fill_list(json_data[0].children)
		})
		.fail(function(a, b, err){
			alert(err)
		})
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEqRecipeList"), 
			data:JSON.stringify({
				"eqName": eqn,
				"rcpType":"dummy",
				"unitName":"",
				"location":false
			}),
			dataType: 'json',
			success: function (json_data) {
				//console.log(JSON.parse(json_data.d))
				__rcp_dummy_fill_list(JSON.parse(json_data.d)[0].children)
			},
			error: function (response) {
				alert('Error: ' + response.responseText)
			}
		})
	}
}

function __rcp_dummy_show_recipe(dummy_rcp_name)
{
	// get dummy recipe file content
	if (ams_is_sim_mode()) {
		var sample_filename = '../recipe_files/recipe_dummy_new.json'
		$.getJSON(sample_filename, 
		function(json_data) {
			__rcp_dummy_draw_canvas(json_data)
		})
		.fail(function(a, b, err){
			alert(err)
		})
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEquipDummyRecipe"), 
			data:JSON.stringify({
				"eqName": eqn,
				"rcpName": dummy_rcp_name,
			}),
			dataType: 'json',
			success: function (json_data) {
				__rcp_dummy_draw_canvas(JSON.parse(json_data.d))
			},
			error: function (response) {
				alert('Error: ' + response.responseText)
			}
		})
	}
}

function __rcp_dummy_draw_canvas(jdata)
{
	g_current_dummy_cnt = jdata
	var the_canvas = document.getElementById('rcp_dummy_canvas');
	var ctx = the_canvas.getContext("2d");

	ctx.clearRect(0, 0, the_canvas.width, the_canvas.height)
	ctx.textBaseline = 'middle'
	ctx.textAlign = "center"

//	console.log(jdata)
	var img_bg = document.createElement("img")
	img_bg.src = '../img/' + jdata.dummy_img + ".jpg"
	img_bg.onload = function() {
		ctx.drawImage(img_bg, 0, 0, img_bg.width, img_bg.height)
		ob_array = jdata.dummy_node_array
		for (var i = 0; i < ob_array.length; i++) {
			var ob = ob_array[i]
			var disp_txt = ""
			if (ob.ctype == "btn") {
				if (ob.dtype == 'int' && ob.enum != undefined)
					disp_txt = ob.enum.split('|')[parseInt(ob.value)]
				else
					disp_txt = ob.value
				__rcp_dummy_create_btn(ctx, parseInt(ob.x), parseInt(ob.y),
					parseInt(ob.width), parseInt(ob.height), disp_txt)
			} else if (ob.ctype == "txt") {
				disp_txt = ob.name
				__rcp_dummy_create_label(ctx, parseInt(ob.x), parseInt(ob.y),
					parseInt(ob.width), parseInt(ob.height), disp_txt)
			}
		}
	}
}

function __rcp_dummy_create_btn(ctx, x, y, w, h, txt)
{
    ctx.fillStyle = "#555555"
    ctx.fillRect(x+1, y+1, w, h)
    ctx.fillStyle = "#dddddd"
    ctx.fillRect(x, y, w, h)

    ctx.fillStyle="#000000"
    ctx.font = "14px Arial"
    ctx.fillText(txt, x + w/2, y + h/2, w)
}

function __rcp_dummy_create_label(ctx, x, y, w, h, txt)
{
    ctx.fillStyle="#000000"
    ctx.font = "14px Arial"
    ctx.fillText(txt, x + w/2, y + h/2, w)
}

function __rcp_dummy_update_btn(x, y, w, h, txt)
{
	var the_canvas = document.getElementById('rcp_dummy_canvas')
	var ctx = the_canvas.getContext("2d")

    ctx.fillStyle = "#dddddd"
    ctx.fillRect(x, y, w, h)

    ctx.fillStyle="#0000ff"
    ctx.font = "14px Arial"
    ctx.fillText(txt, x + w/2, y + h/2, w)
}

// TODO: move this to ams.util.js
function getLocation(canvas, x, y)
{
	var bbox = canvas.getBoundingClientRect();
	return {
		x: (x - bbox.left) * (canvas.width / bbox.width),
		y: (y - bbox.top) * (canvas.height / bbox.height)
	};
}

var g_enum_pump_rcp_dlg_ok_handler = null
var g_enum_val_dlg_ok_handler = null
var g_input_val_dlg_ok_handler = null
function rcp_dummy_init_mouse_event()
{
	rcp_dummy_canvas.onmousemove = function(e)
	{
		if (g_current_dummy_cnt == null)
			return

		var location = getLocation(this, e.clientX, e.clientY)
		
		for (var i = 0; i < g_current_dummy_cnt.dummy_node_array.length; i++) {
			var ob = g_current_dummy_cnt.dummy_node_array[i]
			if (location.x >= parseInt(ob.x) && location.x <= (parseInt(ob.x) + parseInt(ob.width)) &&
				location.y >= parseInt(ob.y) && location.y <= (parseInt(ob.y) + parseInt(ob.height)) &&
				(ob.ctype == "btn"))
			{
				this.style.cursor = 'pointer'
				return
			}
		}
		this.style.cursor = 'auto'
	}

	rcp_dummy_canvas.onmousedown = function(e)
	{
		if (g_current_dummy_cnt == null)
			return
			
		var location = getLocation(this, e.clientX, e.clientY)
		
		for (var i = 0; i < g_current_dummy_cnt.dummy_node_array.length; i++) {
			var ob = g_current_dummy_cnt.dummy_node_array[i]
			var _x = parseInt(ob.x)
			var _y = parseInt(ob.y)
			var _w = parseInt(ob.width)
			var _h = parseInt(ob.height)
			if (location.x >= _x && location.x <= (_x + _w) &&
				location.y >= _y && location.y <= (_y + _h) &&
				(ob.ctype == "btn"))
			{
				if (checkUserLevel() == false){
					return;
				}
				
				if (ob.enum != undefined) {
					if (ob.enum == "pump") {
						g_enum_pump_rcp_dlg_ok_handler = function(val) {
							__rcp_dummy_set_val(ob.name, ob.value, val, "")
							// update 'button' value
							__rcp_dummy_update_btn(_x, _y, _w, _h, val)
							ob.value = val
						}
						// browser pump recipe (rcp_select_dlg)
						$('#rcp_select_dlg').dialog('open') // must be opened before init controls!!!
						__rcp_dummy_enum_rcp('pump') // fill tree grid 'rcp_select_tg' in rcp_select_dlg
					} else {
						g_enum_val_dlg_ok_handler = function(val, index) {
							console.log(val, index)
							var write_val = ((ob.dtype == "int") ? index : val)
							__rcp_dummy_set_val(ob.name, ob.value, write_val, ob.enum)
							// update 'button' value
							__rcp_dummy_update_btn(_x, _y, _w, _h, val)
							ob.value = val
						}
						$('#enum_value_dlg').dialog('open') // must be opened before init controls!!!
						__enum_dlg_load_values(ob.enum, '|', ob.value, ob.dtype)
					}
				} else {
					g_input_val_dlg_ok_handler = function(val) {
						console.log(val)
						if (ob.llimit != undefined) {
							var ll = parseFloat(ob.llimit)
							var ul = parseFloat(ob.ulimit)
							var fval = parseFloat(val)
							if (fval < ll || fval > ul) {
								alert('value out of range. ')
								return
							}
						}
						__rcp_dummy_set_val(ob.name, ob.value, val, "")
						// update 'button' value
						__rcp_dummy_update_btn(_x, _y, _w, _h, val)
						ob.value = val
					}
					$('#input_value_dlg').dialog('open')
					$('#input_val_box').textbox('setText', ob.value)
					if (ob.llimit != undefined)
						$('#input_lowlimit').textbox('setText', ob.llimit)
					if (ob.ulimit != undefined)
						$('#input_uplimit').textbox('setText', ob.ulimit)
				}
				return
			}
		}
	}
}

// 20190624 start
function __rcp_dummy_enum_rcp(rcp_type)
{
	if (ams_is_sim_mode()) {
		$.getJSON('recipe_list_eq_pump_01.json', 
			function(json_data) {
				console.log(json_data)
				$("#rcp_select_tg").treegrid({
					url : 'recipe_list_eq_pump_01.json',
				//	data : json_file_list_data,
					method : 'get',
					idField: 'id',
					treeField: 'name'})
			})
			.fail(function(a, b, err){
				alert(err)
		})	
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEqRecipeList"),
			data:JSON.stringify({
				"eqName":eqn,
				"rcpType":rcp_type,
				"unitName":"",
				"location":false
			}),
			dataType: 'json',
			success: function (json_data) {
				$('#rcp_select_tg').treegrid({
					data:JSON.parse(json_data.d),
					idField : 'id',
					treeField : 'name'
				})
			}
		})
	}
}
// 20190624 end

function __rcp_dummy_set_val(vname, preVal, val, enumVal)
{
	if (checkUserLogin() == false)
		return;
		
	if (ams_is_sim_mode()) {
		console.log('[dummy write] ' + vname + ' = ' + val)
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("setConfigValue"), 
			data:JSON.stringify({
				"userLogin": "",
				"eqName": eqn,
				"ecName": vname,
				"ecValue": val,
			}),
			dataType: 'json',
			success: function (json_data) {
				if (JSON.parse(json_data.d) == 0) {
					$('#enum_value_dlg').dialog('close')
					$('#rcp_select_dlg').dialog('close')
					$('#input_value_dlg').dialog('close');
					if (enumVal.length > 0){
						var arrEnumVal = enumVal.split("|");
						preVal = arrEnumVal[parseInt(preVal)];
						val = arrEnumVal[parseInt(val)];
					}
					var info = "Set dummy value(" + vname + ") from \\'" + preVal + "\\' to \\'" + val + "\\'.";
					add_log_to_server(eqn, "dummy", info);
					$.messager.alert("AMS", "Set dummy value ok.", "info")
				} else {
					$.messager.alert("AMS", "Set dummyu value failed.", "info")
				}
			},
			error: function (response) {
				alert('Error: ' + response.responseText)
			}
		})
	}
}

function __enum_dlg_load_values(enum_def_str, delimiter, vCur, dtype)
{
	var val_array = enum_def_str.split(delimiter)
//	console.log(val_array)
	$('#enum_val_list').datalist('loadData',[])
	for (var k = 0; k < val_array.length; k++) {
		$('#enum_val_list').datalist('appendRow',{
				value:val_array[k],
				text:val_array[k]
			})
		if (dtype == "string" && vCur == val_array[k]) {
			$('#enum_val_list').datalist('selectRow', k)
		}
		if (dtype == "int" && parseInt(vCur) == k) {
			$('#enum_val_list').datalist('selectRow', k)
		}
	}
}

function on_rcp_dummy_refresh_list()
{
	__rcp_dummy_load_list()
	__rcp_dummy_clear_canvas()
}
// 20190613 end

function getFullPathName(_grid_name,name,id)
{
	var pathName = ""
	var parentRow = $(_grid_name).treegrid('getParent', id)
	while (parentRow != null)
	{
		pathName = parentRow.name + '/' + pathName
		parentRow = $(_grid_name).treegrid('getParent', parentRow.id)
	}
	pathName = pathName + name
	return pathName	
}

function get_Unit_type(_grid_name,type,row)
{
	var pathName = ""
	var current_row = ''
	//if (row.name != type){
	if (row._parentId != undefined){
	var parentRow = $(_grid_name).treegrid('getParent', row.id)
	if (parentRow.name != type){
	while (parentRow.name != type)
	{
		current_row = parentRow
		pathName = parentRow.name + '/' + pathName
		parentRow = $(_grid_name).treegrid('getParent', parentRow.id)
	}
	unit_type = current_row.name
	pathName = pathName + row.name
	return unit_type
}
	else{
		unit_type = type
		return unit_type
	}
	}}

function onContextMenu(e,row)
{
	e.preventDefault()
    $(this).treegrid('select', row.id) //选中当前行
    $('#eq_unit_context_menu').menu('show', {
        left: e.pageX,
        top: e.pageY
    })
}

function copy()
{
	var __grid_name = '#server_rcp_tabs'
	var tab = $(__grid_name).tabs('getSelected')
	var index = $(__grid_name).tabs('getTabIndex',tab)
	var row
	var rcp_type
	var parentName
	var childrenRow
	var unit_type
	var path
		if (index == '0'){
			row = $('#server_rcp_proc').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			copy_rcp_type = 'process'
			if (row.name == 'process'){
				parentName = 'process'
			}else{
			parentName = $("#server_rcp_proc").treegrid('getParent', row.id).name}
			childrenRow = $("#server_rcp_proc").treegrid('getChildren', row.id)
			copy_path_1 = getFullPathName(server_rcp_proc,row.name,row.id)
			unit_type = 'process'
		}}else if (index == '1'){
			row = $('#server_rcp_unit').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			copy_rcp_type = 'unit'
			if (row.name == 'unit'){
				parentName = 'unit'
			}else{
			parentName = $("#server_rcp_unit").treegrid('getParent', row.id).name}
			childrenRow = $("#server_rcp_unit").treegrid('getChildren', row.id)
			copy_path_1 = getFullPathName(server_rcp_unit,row.name,row.id)
			unit_type = get_Unit_type(server_rcp_unit,'unit',row)
		}}else if (index == '2'){
			row = $('#server_rcp_pump').treegrid('getSelected')
			if (!row) {
				$.messager.alert("Tips", "Select a recipe file please.", "info");
				return
			}else {
			copy_rcp_type = 'pump'
			if (row.name == 'pump'){
				parentName = 'pump'
			}else{
			parentName = $("#server_rcp_pump").treegrid('getParent', row.id).name}
			childrenRow = $("#server_rcp_pump").treegrid('getChildren', row.id)
			copy_path_1 = getFullPathName(server_rcp_pump,row.name,row.id)
			unit_type = get_Unit_type(server_rcp_pump,'pump',row)
		}}
	copy_unit_type = unit_type
	g_cmp_eq_1 = get_page_param('eq')
	g_copy_rcpfn_1 = row.name
	g_copy_loc_1 = 'server'

	$('#rcp_copy_sel_wnd').window({title:'Select a path to copy with:  [' + g_copy_rcpfn_1 + ']'}).window('open')
	refresh_rcp_cmp_sel_wnd_eq_tree()
	document.getElementById("path_rcp_subtype").innerHTML = copy_unit_type
	document.getElementById("path_rcp_1").innerHTML = get_page_param('eq') + '/' + copy_path_1;//path 
}

function rename()
{
	$('#dlg_rcp_rename').dialog('open')
	if (new_rcp_name == '') {
		$.messager.alert("Tips", "Recipe name can\'t be empty.", "info");
		return
	}
	document.getElementById("rename_old").innerHTML = old_name
	// new_name = document.getElementById('new_rcp_name').value
}

function do_rename()
{
	if (checkUserLevel() == false){
		return;
	}
			
	var new_rcp_name = document.getElementById('new_rcp_name').value
	$('#dlg_rcp_rename').dialog('open')
	if (new_rcp_name == '') {
		$.messager.alert("Tips", "Recipe name can\'t be empty.", "info");
		return
	}
	new_name = document.getElementById('new_rcp_name').value
	if (ams_is_sim_mode()) {
		$.messager.alert("Tips", "New Name: " + new_name, "info");
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("renameRecipe"), 
			data:JSON.stringify({
				"eqName": eqn,
				"rcpOldName": old_name,
				"rcpNewName": new_rcp_name,
				"rcpType": rename_type,
				"rcpUnitType":rename_unit_type,
				"rcpPath":rename_path,
				"location":true
			}),
			dataType: 'json',
			success: function (json_data) {
				// add log to server
				var opContext = "Rename recipe from [" + rename_path+  "] to [" + new_rcp_name + "].";
				add_log_to_server(eqn, "recipe", opContext);
				if (JSON.parse(json_data.d) == 0) {
					$('#dlg_rcp_rename').dialog('close')
					$.messager.alert("AMS", opContext, "info")
				} else {
					$.messager.alert("AMS", "Rename failed.", "info")
				}
			},
			error: function (response) {
				alert('Error: ' + response.responseText)
			}
		})
	}

}

// 2019-06-30 17:28, jxb
function BatchUpload()
{
	if (checkUserLevel() == false){
		return;
	}
	
	$.messager.confirm('AMS System',
	'Are you sure the batch upload recipe to the server?<br>Note: Files with the same name will be replaced!',
	function(r) {
		if (r){
			var treeId = "";
			var tab = $('#eq_rcp_tabs').tabs('getSelected');
			var index = $('#eq_rcp_tabs').tabs('getTabIndex',tab);
			if (index == '0'){
				treeId = '#eq_rcp_proc';
			}
			else if (index == '1'){
				treeId = '#eq_rcp_unit';
			}
			else{
				treeId = '#eq_rcp_pump';
			}
			
			var node = $(treeId).treegrid('getSelected');
			var chRow = isLeaf(treeId,node.id)
			if (chRow.length > 0){
				var nodeChildren = $(treeId).treegrid("getChildren",node.id);
				for (var i = 0; i < nodeChildren.length; i++){
					if (isLeaf(treeId,nodeChildren[i].id).length == 0){
						$(treeId).treegrid("select",nodeChildren[i].id);
						on_upload_rcp(true);
					}
				}
			}
			else{
				on_upload_rcp(true);
			}
			on_refresh_rcp_list('server');
			$.messager.alert("Tips", "Batch upload successful.", "info");
		}
	});
}

$(function () {
   $('#rcp-group-equ').combobox({
        onChange: function (newValue, oldValue) {
        	set_recipe_group('eq', false);
        	on_refresh_rcp_list('eq')
          //load_rcp_list('eq', 'process');
					//load_rcp_list('eq','unit');
					//load_rcp_list('eq','pump');
        }
    });
});

$(function () {
   $('#rcp-group-svr').combobox({
        onChange: function (newValue, oldValue) {
        	set_recipe_group('server', false);
        	on_refresh_rcp_list('server');
					//load_rcp_list('server', 'process');
					//load_rcp_list('server','unit');
					//load_rcp_list('server','pump');
        }
    });
});

$(function () {
   $('#eq_rcp_tabs').tabs({
        onSelect: function (title, index) {
        	select_tab_reload_rcp_list(index, 'eq');
        }
    });
});

$(function () {
   $('#server_rcp_tabs').tabs({
        onSelect: function (title, index) {
					select_tab_reload_rcp_list(index, 'server');
					//$("#server_rcp_proc").treegrid('reload');
        }
    });
});

function select_tab_reload_rcp_list(index, location){
	switch (index){
		case 0:
			rcp_type = 'process';
			break;
		case 1:
			rcp_type = 'unit';
			break;
		case 2:
			rcp_type = 'pump';
			break;
		default:
			break;
	}
	reload_rcp_list(location, rcp_type)
}